Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

javascript - 在状态下反应getDerivedStateFromProps更新数组(React getDerivedStateFromProps update array in state)

I have a problem with updating component state by getDerivedStateFromProps.

(我通过getDerivedStateFromProps更新组件状态时遇到问题。)

In my component state I have few arrays, but returning value in getDerivedStateFromProps doesn't seem to update them at all :<

(在我的组件状态下,我只有几个数组,但是在getDerivedStateFromProps中返回值似乎根本没有更新它们:)

My code:

(我的代码:)

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
}
  ask by jStefko translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...