【问题标题】:How to initialize this.props into this.state如何将 this.props 初始化为 this.state
【发布时间】:2019-11-06 07:15:31
【问题描述】:

一个道具中有多个输入值,但我需要的值是状态。据说不要初始化 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

【问题讨论】:

  • 不,此语法不正确,您无法在子组件中初始化 props,您只能在父组件中初始化或更改其值。
  • 好的,有什么替代方案 b'cos this.props.sale 来自 GraphQL 数据库。
  • 所以,您想更改 this.props.sale 的值,或者想保存您的具体问题并分享您的代码,以便我们为您提供帮助。
  • 我要更改 this.props.sale 的值
  • 请分享您的代码

标签: reactjs react-native react-apollo


【解决方案1】:

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

【讨论】:

  • 所以我上面的语法是正确的?因为我在 state 中保存了一份 props 的副本
【解决方案2】:

您可以在组件挂载时将 prop 值传递给 state。您可以使用componentDidMount 生命周期方法执行以下操作:

componentDidMount() {

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

  }

这样,当组件挂载时,您的状态值rent 将是this.props.house.rent 的值。然后,您可以对 state 中需要的每个 props 执行此操作。

更多关于 ComponentDidMount 的信息可以在React Documentation找到

【讨论】:

  • 您可能希望在componentDidUpdate 中执行此操作,因此每次道具更改时它都会设置状态。除非 OP 不希望这是当然的预期副作用 :)
  • componentDidUpdate 中设置状态会造成无限循环并导致崩溃。如果这是必需的,则需要采取防御措施。
【解决方案3】:

您可以使用扩展运算符像这样使用道具初始化状​​态

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
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    • 2021-10-30
    • 2010-11-15
    • 1970-01-01
    相关资源
    最近更新 更多