首页 > 解决方案 > React getDerivedStateFromProps 更新状态数组

问题描述

我在通过 getDerivedStateFromProps 更新组件状态时遇到问题。在我的组件状态中,我的数组很少,但是 getDerivedStateFromProps 中的返回值似乎根本没有更新它们:<

我的代码:

static getDerivedStateFromProps (nextProps, prevState) {
let result = null

// always the same
// nextProps.mainObject have all data I need
// but all component state arrays are empty

if (nextProps.mainObject && nextProps.mainObject.parameters && nextProps.mainObject.parameters.length &&
  !_.isEqual(nextProps.mainObject.parameters, prevState.parameters)) {
  result = {
    parameters: nextProps.mainObject.parameters
  }

  let parameterOneList = nextProps.mainObject.parameters.filter(item => item.type === 'one')
  let parameterTwoList = nextProps.mainObject.parameters.filter(item => item.type === 'two')
  let parameterThreeList = nextProps.mainObject.parameters.filter(item => item.type === 'three')

  if (!_.isEqual(parameterOneList, prevState.parameterOneList)) {
    result.parameterOneList = parameterOneList
  }
  if (!_.isEqual(parameterTwoList, prevState.parameterTwoList)) {
    result.parameterTwoList = parameterTwoList
  }
  if (!_.isEqual(parameterThreeList, prevState.parameterThreeList)) {
    result.parameterThreeList = parameterThreeList
  }
}

if (nextProps.mainObject && nextProps.mainObject.otherParameters && nextProps.mainObject.otherParameters.length &&
  !_.isEqual(nextProps.mainObject.otherParameters, prevState.otherParameters)) {
  // check if result was changed already by parameters
  if (result) {
   result.otherParameters = nextProps.mainObject.otherParameters
  } else {
    result = {
     otherParameters: nextProps.mainObject.otherParameters
    }
  }
}

// always the same
// all data in result looks great, arrays are filled with data

return result
}

标签: javascriptreactjs

解决方案


您可以尝试将所有数组属性分配nextProps给常量它应该可以工作:

    static getDerivedStateFromProps(nextProps, prevState) { 
        const _anyArray = nextProps.anyArray
        return {
           anyArray: _anyArray
        }
    }

推荐阅读