在 React 组件中在哪里设置依赖于道具的状态?
Where to set props-dependant state in a React component?
假设我想根据通过 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 = {...}
吗?还是属于ComponentWillMount()
?如果是这样,是否能保证状态会及时呈现? (foo
显示为文本字段)
由于你的state是根据proper的值赋值的,所以比较好的处理方式是在两个地方赋值
ComponentWillMount/Constructor/ComponentDidMount:这些仅在安装组件时执行一次。还有一件事是,如果你在 componentWillMount 或 componentDidMount 中设置状态,它应该至少在构造函数中初始化,这样你就不会得到未定义的状态错误。
ComponentWillReceiveProps:这个 lifeCyle 函数在挂载时不会被调用,但每次父级重新渲染后都会被调用,所以任何时候 prop foo 从父级发生变化,它都可以在这里再次分配给 state
喜欢
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'});
}
}
是的,在构造函数中初始化状态是有效的:React Constructor Docs
所以你的代码如下:
class MyClass extends Component {
constructor(props) {
super(props);
if (props.foo === 'bar') {
this.state = {foo: 'bar'};
} else {
this.state = {foo: 'notBar'};
}
}
}
但是,请注意,对父项中的道具所做的任何更改都不会在此组件中更新,因为它仅在构造函数中设置。
因此,如果您不希望父 props 发生变化(但这可能很少见),这只是初始化状态的好方法。查看 Lifting State Up 以获取以更好的方式构建组件的指南。
假设我想根据通过 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 = {...}
吗?还是属于ComponentWillMount()
?如果是这样,是否能保证状态会及时呈现? (foo
显示为文本字段)
由于你的state是根据proper的值赋值的,所以比较好的处理方式是在两个地方赋值
ComponentWillMount/Constructor/ComponentDidMount:这些仅在安装组件时执行一次。还有一件事是,如果你在 componentWillMount 或 componentDidMount 中设置状态,它应该至少在构造函数中初始化,这样你就不会得到未定义的状态错误。
ComponentWillReceiveProps:这个 lifeCyle 函数在挂载时不会被调用,但每次父级重新渲染后都会被调用,所以任何时候 prop foo 从父级发生变化,它都可以在这里再次分配给 state
喜欢
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'});
}
}
是的,在构造函数中初始化状态是有效的:React Constructor Docs
所以你的代码如下:
class MyClass extends Component {
constructor(props) {
super(props);
if (props.foo === 'bar') {
this.state = {foo: 'bar'};
} else {
this.state = {foo: 'notBar'};
}
}
}
但是,请注意,对父项中的道具所做的任何更改都不会在此组件中更新,因为它仅在构造函数中设置。
因此,如果您不希望父 props 发生变化(但这可能很少见),这只是初始化状态的好方法。查看 Lifting State Up 以获取以更好的方式构建组件的指南。