尝试从道具更新状态时反应麻烦

时间:2019-03-14 17:54:10

标签: reactjs state react-props

今天,我来找您是因为我在构建应用程序时遇到了一些问题, 我正在尝试做的是在父状态更新时更新组件状态,我已经尝试从那里选择解决方案,但没有一个起作用

这是我的子组件的外观:

class SideBarSimu extends component{
  constructor(props){
    this.state = {
      addedConfigs: { },
      // should looks like { key1: { property1: {} , property2: {}}, ... }
      cached: {  },
      // used to compare the addedConfig[key] im editing with the new prop
      editing: null, // the addedConfig key im currently edting
      ...
    }
  }
  // here i put the methods im trying
  ...
  render(){
    ...
  }
}

这是到目前为止我尝试过的事情:

componentWillReceiveProps(nextProps){
    console.log(this.state.cached)
    console.log(nextProps.moduleDetails)
    if(nextProps.moduleDetails !== this.props.moduleDetails && this.state.editing !== null){
      let temp = this.props.getModules() // returns the parent's state i need to store into this.state.addedConfigs[key], can't use this.props because i need to add extra keys
      let configs = {...this.state.addedConfigs}
      configs[this.state.editing] = temp
      this.setState({ addedConfigs: configs })
    }
  }

那根本没有用,所以我尝试了:

static getDerivedStateFromProps (nextProps, prevState) {
    if(nextProps.moduleDetails !== prevState.cached && prevState.editing !== null) {
      let temp = nextProps.getModules()
      let config = {...prevState.addedConfigs}
      config[prevState.editing] = temp
      return {
        addedConfigs: config, 
        cached: nextProps.moduleDetails
      };
    } else {
      return null
    }
  }

这是我最后尝试过的事情:

shouldComponentUpdate(nextProps, nextState){
    if(nextProps.moduleDetails !== nextState.cached && nextState.editing !== null){
      let temp = this.props.getModules()
      let config = {...nextState.addedConfigs}
      config[nextState.editing] = temp
      this.setState({ addedConfigs: config, cached: nextProps.moduleDetails })
    }
    return true
  }

我第一次分配this.state.editing实际上是有效的,但是当我对父母的状态进行更改时,它不会验证if语句,因此我认为我可能会误会那里的东西

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

在这里我已修复它,我只是更改了条件,现在它可以按我期望的那样工作。我也删除了缓存状态,因为我不再需要它。

我的代码:

static getDerivedStateFromProps (nextProps, prevState) {
    if(prevState.editing !== null) {
      let temp = nextProps.getModules()
      let config = {...prevState.addedConfigs}
      config[prevState.editing] = temp
      return {
        addedConfigs: config, 
      };
    } else {
      return null
    }
  }