尝试从 props 更新状态时出现问题

React Troubles when trying to update states from props

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

这是我的子组件的样子:

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 语句,所以我想我可能误解了那里的东西

任何帮助将不胜感激

我已经修复了它,我只是改变了条件,现在它可以正常工作了。我也删除了我的缓存状态,因为我不再需要它了。

我的代码:

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
    }
  }