在状态下反应getDerivedStateFromProps更新数组

时间:2019-11-28 15:33:08

标签: javascript reactjs

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

我的代码:

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
}

1 个答案:

答案 0 :(得分:0)

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

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