【问题标题】:react child props does not update when sending updated parent state发送更新的父状态时反应子道具不更新
【发布时间】:2020-02-14 16:33:34
【问题描述】:

我有一个图表组件,我正在通过道具数据从 api 获取数据以放入图表,但是当我将父级作为道具发送到图表组件时,它并没有更新父状态,而是更新了子道具没有更新,如果我登录

componentWillReceiveProps(props) {
  console.log(props);
  // it shows updated value but if i do this 
  this.loadData();
}

loadData = () => {
  console.log(props)
  // it's value is old and not updated 
}

我已在父项中检查它,状态已更新,当我第一次单击它时,我在父项中有一个单击事件,父状态会更改,但图表组件道具不会更改,如果我第二次单击图表组件道具,状态会发生变化第一次点击状态

这是我的 github 仓库 https://github.com/naveenkash/forex 在通过index.js获取props时查看图表组件props和pages index.js图表​​

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    因为 componentWillReceiveProps 中的 props 是对新 props 的引用,它们在类的其他部分尚不可用,所以你应该将它们传递给 loadData

    componentWillReceiveProps(props){
       this.loadData(props);
    }
    
    loadData=(props)=>{
       console.log(props)
    }
    

    【讨论】:

    • 但是当我的状态改变时,我的道具也应该改变。这就是我现在正在做的在我的加载函数中传递数据
    • 您没有在示例中传递 props 值
    • @disfatbidge,你真的不应该强迫人们通过你的代码来寻找一个简单而狭隘的问题
    【解决方案2】:

    Dmitry 所说的是准确的,this.propscomponentWillReceiveProps(props) 一样没有改变。因此,当您调用 this.loadData() 时,您仍然使用旧道具调用它。

    请注意,componentWillReceiveProps(props)unsafe

    您应该使用componentDidUpdate(previousProps),您可以在其中调用this.loadData(),它将使用更新的this.props 执行。

    【讨论】:

    • 在循环中使用 componentDidUpdate 会不断在 componentDidUpdate 中调用我的函数
    • componentDidUpdate 更新时如何接收 previousProps 不会得到新的 props
    • 您需要检查previousPropsthis.props——即如果您只想在this.props.ID 更改时更新,那么您有条件地调用this.loadData()if (this.props.ID === prevProps.ID) { return; }。由于componentDidUpdate(prevProps) 是在更新后调用的,因此您在this.props 中有新的道具。所以要获得新的道具,你可以打电话给this.props,要获得以前的道具,你可以打电话给prevProps
    【解决方案3】:

    这是 js 范围问题不响应事件提升周期问题,考虑更改代码如下:

    componentWillReceiveProps(props) {
      console.log(props);
      // it shows updated value but if i do this 
      this.loadData(props);
    }
    
    loadData = (newProps) => {
      console.log(newProps)
      // it's value is old and not updated 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 2018-01-13
      • 2016-09-18
      • 2021-03-31
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      相关资源
      最近更新 更多