Javascript 在React组件中的何处设置道具从属状态?
假设我想根据通过Javascript 在React组件中的何处设置道具从属状态?,javascript,reactjs,ecmascript-6,state,Javascript,Reactjs,Ecmascript 6,State,假设我想根据通过props传递的父级变量设置组件的初始状态 class MyClass extends Component { constructor(props) { super(props); this.state = {}; } 我想设置如下状态: if (this.props.foo === 'bar') { this.setState({foo: 'bar'}); } else { this.setState({foo: 'notBar'}); }
props
传递的父级变量设置组件的初始状态
class MyClass extends Component {
constructor(props) {
super(props);
this.state = {};
}
我想设置如下状态:
if (this.props.foo === 'bar') {
this.setState({foo: 'bar'});
} else {
this.setState({foo: 'notBar'});
}
我把它放在
ComponentDidMount()
中,它似乎可以工作。但是,我是否应该将其移动到构造函数并使用语法this.state={…}
?或者它属于组件willmount()
?如果是,是否有保证及时提供该国?(foo
显示为文本字段)由于您的状态是基于property的值分配的,因此处理它的一个好方法是将其分配到两个位置
constructor(props) {
super(props);
this.state = {
foo: ''
}
}
componentWillMount(){
if (this.props.foo === 'bar') {
this.setState({foo: 'bar'});
} else {
this.setState({foo: 'notBar'});
}
}
componentWillReceiveProps(nextProps){
if (nextProps.foo === 'bar') {
this.setState({foo: 'bar'});
} else {
this.setState({foo: 'notBar'});
}
}
是,在构造函数中初始化状态是有效的: 因此,您的代码如下所示:
class MyClass extends Component {
constructor(props) {
super(props);
if (props.foo === 'bar') {
this.state = {foo: 'bar'};
} else {
this.state = {foo: 'notBar'};
}
}
}
但是,请注意,对父级中的道具的任何更改都不会在该组件中更新,因为它只在构造函数上设置
因此,如果您不希望父道具发生更改,那么这是初始化状态的唯一好方法(但这可能很少)。请查看以更好的方式构建组件的指南。我不知道
componentWillReceiveProps()
,谢谢!因此,如果我理解正确,在实践中,使用组件willreceiveprops()
将产生与将getFoo()
作为props而不是foo
传递类似的结果?(其中getFoo()
是一个父方法,返回从父状态读取的foo
值)类似,但可以一次处理更多的道具。凯,我一直在使用将getter函数作为道具传递的方法,所以知道一个更干净的替代方法很好。谢谢很高兴能为您提供帮助,我建议您阅读React文档,以了解更多有关lifcycle功能的信息。他们帮了大忙