javascript - 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
}
解决方案
您可以尝试将所有数组属性分配nextProps
给常量它应该可以工作:
static getDerivedStateFromProps(nextProps, prevState) {
const _anyArray = nextProps.anyArray
return {
anyArray: _anyArray
}
}
推荐阅读
- java - 向 hashCode() 添加数字是为了什么?
- assembly - 有人可以确认 push r64 应该是 50+ro 而不是 +rd 吗?英特尔文档中的错误?
- firebase - 通过“createCustomToken”方法发布时,CustomToken 不起作用
- c# - 新的 Microsoft.NET.Sdk 项目在子目录中构建输出文件。怎么改回来?
- javascript - 使用 AAD 访问 .Net Web Api 的 JQuery 抛出 401 invalid_token / 发行者无效
- css - HTML / SASS 元素的属性值无效
- sql - 如何限制 DBeaver 数据编辑器以限制结果集大小?
- sql-server - SQL 删除并取回字段
- javascript - "找到) 当期望 (" Java 脚本
- angular - 如何重写谷歌地理图表的代码以将其与角度(angular-google-charts)一起使用?