【问题标题】:Updating component's state using props使用 props 更新组件的状态
【发布时间】:2018-10-24 10:45:20
【问题描述】:

我正在尝试以这种方式使用接收到的道具更新某些组件的状态:

componentWillReceiveProps(nextProps) {
   if(nextProps.history.length <= 2) {
      this.setState({
         history: nextProps.history
      });
   }
}

问题在于,当父级传递长度大于 2 的历史时,状态仍在变化。有什么想法吗?

谢谢

【问题讨论】:

  • ..当父级传递长度大于 2 的历史记录时,状态仍在变异。 -- 你确定状态更新仅来自这个@987654322 @钩子?
  • 您还应该检查 nextProps 是否与 Props 不同。如果不是,则无需更新您的状态。
  • Arup - 是的,这是我组件状态唯一可能发生变化的地方...
  • 一个codesandbox将在这里帮助调试
  • 这是答案(我的朋友帮我解决了这个问题):当传递一些“大对象”(不是像整数或字符这样的原始对象)时,浏览器通过引用传递对象而不是复制它。那就是问题所在。所以解决方案是 - 如果您不想依赖于代码中其他地方所做的更改,请传递一个副本(无论是否深)

标签: javascript reactjs


【解决方案1】:

生命周期方法componentWillReceiveProps 已弃用。你应该使用getDerivedStateFromProps

getDerivedStateFromProps 在调用 render 方法之前被调用,无论是在初始挂载时还是在后续更新时。它应该返回一个对象来更新状态,或者返回 null 以不更新任何内容。

【讨论】:

    【解决方案2】:

    您可以使用 componentDidUpdate() 生命周期方法或 静态getDerivedStateFromProps() 方法。

    static getDerivedStateFromProps(props, state) {
        return ({
            history: props.history.length <= 2 ? props.history : state.history
        })
    }
    

    或者,如果您愿意:

    componentDidUpdate(prevProps) {
        const { history } = this.props;
        if((prevProps.history !== history) && history.length <= 2) {
            this.setState({ history })
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-02
      • 1970-01-01
      • 2019-08-31
      • 2018-11-23
      • 2017-07-28
      • 2019-09-29
      • 2021-04-26
      • 2020-09-30
      • 1970-01-01
      相关资源
      最近更新 更多