如何将this.props初始化为this.state

时间:2019-06-24 13:07:15

标签: reactjs react-native react-apollo

道具中有多个输入值,但我需要的值处于状态。据说我不初始化this.props = this.state,因为props是只读的。

我尝试过this.props = this.state,它确实起作用。

const prevHouse = this.props.house; // This has multiple input values

prevHouse.rent = this.state.rent; //State is given input value

以上语法使用正确吗,对此有什么解决方案?

更新:将this.props.house更改为上面的prevHouse

3 个答案:

答案 0 :(得分:1)

您可以在安装组件时将prop值传递给状态。您可以使用componentDidMount生命周期方法进行以下操作:

componentDidMount() {

    this.setState({
      rent: this.props.house.rent
    })

  }

这样,当组件装入状态值rent时,将成为this.props.house.rent的值。然后,您可以为状态中需要的每个道具执行此操作。

有关ComponentDidMount的更多信息,请访问React Documentation

答案 1 :(得分:1)

您可以复制道具并放入状态。如果您的目标是从子级更改父级组件状态中的状态。您需要使用Context Api或Redux

答案 2 :(得分:0)

您可以使用传播运算符使用类似的道具初始化相同的状态

constructor(props) {
    super(props)

    this.state = {
        ...props //this mean the value of state will filled with all of the object values in props object without need assigning one by one object values
    }

}