在react componentDidUpdate不更新状态

时间:2018-09-07 14:36:42

标签: javascript reactjs

我需要使用进入组件的道具来更新状态(start_date),但是setState并没有更新状态。相反,我得到的值是undefined

这就是我在代码中正在做的事情:

constructor(props) {
  super(props);
  this.state = {
    start_date: ''
  };
}

componentDidUpdate(prevProps, prevState) {
  console.log("prevProps ", prevProps)
  console.log("prevState ", prevState)
  if (prevProps.currentRelease != prevState.currentRelease) {
     console.log("Inside componentDidUpdate ")
     this.setState({
    //  start_date: prevProps.currentRelease.start
    });
  }
}

这是我的数据的屏幕快照,该数据是从父组件传入的,并将其传递给子组件:

data

我需要使用 currentRelease.start (红色框)

更新start_date状态

2 个答案:

答案 0 :(得分:1)

我推荐这个。而不是componentDidupdate

static getDerivedStateFromProps(props, state) {
    const { currentRelease } = props;

    if(currentRelease && currentRelease.start) {
        return { start_date: props.currentRelease.start }
    }

    return null;
}

参考:https://reactjs.org/docs/react-component.html#updating

答案 1 :(得分:0)

问题是,您正在使用prevProps(使用旧版本)更新状态。

您应该使用this.props的{​​{1}}(当前)道具:

正确的代码:

prevProps

您输入的错误代码:

this.setState({
//  start_date: this.props.currentRelease.start
});

在您的代码中,我将 this.setState({ // start_date: prevProps.currentRelease.start }); 替换为prevProps