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的值分配的,因此处理它的一个好方法是将其分配到两个位置

  • ComponentWillMount/Constructor/ComponentDidMount:当安装组件时,这些命令只执行一次。还有一件事是,如果您在componentWillMount或componentDidMount中设置state,那么它至少应该在constructor中初始化,这样您就不会得到未定义的状态错误

  • ComponentWillReceiveProps:此生命周期函数在装载时不被调用,但每次父级重新加载后都会被调用,因此任何时候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'});
        }
    }
    

    是,在构造函数中初始化状态是有效的:

    因此,您的代码如下所示:

    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功能的信息。他们帮了大忙