getDerivedStateFromProps 使用技巧

何时会进入此方法? 组件内setState 与 父组件setState时,会进入此方法。
组件内setState时,该方法返回 null也不会影响渲染;父组件变化时,可以比较props与组件state 的值,从而决定是否返回新的state,会根据返回的结果渲染。
react 源码-ReactFiberClassComponent 处理逻辑
getDerivedStateFromProps(): A valid state object (or null) must be returned.
以下为微信小程序 多列选择器中props 的处理逻辑 微信小程序多列选择器链接
需要注意的是,组件内更新 setState 也会进入 getDerivedStateFromProps,需要判定好条件
options : [ [第一列数据], [第二列所有数据]]

  1. static getDerivedStateFromProps(nextProps, prevState) {
  2. const { value = '',option, rowKey } = nextProps.showInfo || {}
  3. // 根据传入props 更新state
  4. const mutileColumns = option.length
  5. if (prevState.value !== value && mutileColumns > 0) {
  6. let currentValue: number[] = []
  7. const currentArray: any[] = []
  8. const valuePicker = value && value.split(',') || []
  9. // 多列选择 valuePicker option 重新赋值
  10. if(valuePicker.length === 0) {
  11. currentValue= Array(mutileColumns).fill(0)
  12. for (let index = 0; index < mutileColumns; index++) {
  13. currentArray[index] = index>0?option[index][0]: option[0]
  14. }
  15. } else {
  16. for (let index = 0; index < mutileColumns; index++) {
  17. const element = valuePicker[index];
  18. let optionColumn: string[]
  19. if(index > 0) {
  20. const secondIndex = currentValue[index-1]
  21. optionColumn = option[index][secondIndex]
  22. } else {
  23. optionColumn = option[0]
  24. }
  25. const column = optionColumn.findIndex((item) => item[rowKey] === element) || 0
  26. currentValue.push(column)
  27. currentArray[index] = optionColumn
  28. }
  29. }
  30. return {currentValue, currentArray, value }
  31. }
  32. return null;
  33. }

shouldComponentUpdate 使用技巧 pureReactComponent

是否要重新渲染页面,主要用于性能优化。 purecomponent 类似的逻辑
具体可以查看上面源码部分

React 源码还需要阅读