getDerivedStateFromProps 使用技巧
何时会进入此方法? 组件内setState 与 父组件setState时,会进入此方法。
组件内setState时,该方法返回 null也不会影响渲染;父组件变化时,可以比较props与组件state 的值,从而决定是否返回新的state,会根据返回的结果渲染。
react 源码-ReactFiberClassComponent 处理逻辑
getDerivedStateFromProps(): A valid state object (or null) must be returned.
以下为微信小程序 多列选择器中props 的处理逻辑 微信小程序多列选择器链接
需要注意的是,组件内更新 setState 也会进入 getDerivedStateFromProps,需要判定好条件
options : [ [第一列数据], [第二列所有数据]]
static getDerivedStateFromProps(nextProps, prevState) {const { value = '',option, rowKey } = nextProps.showInfo || {}// 根据传入props 更新stateconst mutileColumns = option.lengthif (prevState.value !== value && mutileColumns > 0) {let currentValue: number[] = []const currentArray: any[] = []const valuePicker = value && value.split(',') || []// 多列选择 valuePicker option 重新赋值if(valuePicker.length === 0) {currentValue= Array(mutileColumns).fill(0)for (let index = 0; index < mutileColumns; index++) {currentArray[index] = index>0?option[index][0]: option[0]}} else {for (let index = 0; index < mutileColumns; index++) {const element = valuePicker[index];let optionColumn: string[]if(index > 0) {const secondIndex = currentValue[index-1]optionColumn = option[index][secondIndex]} else {optionColumn = option[0]}const column = optionColumn.findIndex((item) => item[rowKey] === element) || 0currentValue.push(column)currentArray[index] = optionColumn}}return {currentValue, currentArray, value }}return null;}
shouldComponentUpdate 使用技巧 pureReactComponent
是否要重新渲染页面,主要用于性能优化。 purecomponent 类似的逻辑
具体可以查看上面源码部分
React 源码还需要阅读
