如何为setState更新多维json数组中的特定键值对?
How to update specific key-value pair in a multi-dimensional json array for setState?
下面是我处理数据和页面配置的状态 json 数组。
{
auth: {
profile: null,
},
model: {
data: null,
error: null,
},
pageConfig: {
hasHeader: true,
loader: {
isLoaderActive: true,
message: 'Loading...'
},
alert: {
type: null,
message: null
},
redirect: {
url: '/',
data: null
},
}
};
目前,我这边正在更新模型。
this.setState(prevState => ({ ...prevState, model: data }));
很简单,因为它只适用于一个简单的数组,但我想寻求有关如何在维护其他对的同时更新特定键值对(如 isLoaderActive)的指导。
蒂亚
使用 ES6 扩展运算符
const state = {
auth: {
profile: null,
},
model: {
data: null,
error: null,
},
pageConfig: {
hasHeader: true,
loader: {
isLoaderActive: true,
message: 'Loading...'
},
alert: {
type: null,
message: null
},
redirect: {
url: '/',
data: null
},
}
};
const newState = {
...state,
pageConfig: {
...state.pageConfig,
loader: {
...state.pageConfig.loader,
isLoaderActive: false
}
}
}
console.log(newState)
或使用Lodash.set
const state = {
auth: {
profile: null,
},
model: {
data: null,
error: null,
},
pageConfig: {
hasHeader: true,
loader: {
isLoaderActive: true,
message: 'Loading...'
},
alert: {
type: null,
message: null
},
redirect: {
url: '/',
data: null
},
}
};
const newState = _.set(state, 'pageConfig.loader.isLoaderActive', false)
console.log(newState)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
下面是我处理数据和页面配置的状态 json 数组。
{
auth: {
profile: null,
},
model: {
data: null,
error: null,
},
pageConfig: {
hasHeader: true,
loader: {
isLoaderActive: true,
message: 'Loading...'
},
alert: {
type: null,
message: null
},
redirect: {
url: '/',
data: null
},
}
};
目前,我这边正在更新模型。
this.setState(prevState => ({ ...prevState, model: data }));
很简单,因为它只适用于一个简单的数组,但我想寻求有关如何在维护其他对的同时更新特定键值对(如 isLoaderActive)的指导。
蒂亚
使用 ES6 扩展运算符
const state = {
auth: {
profile: null,
},
model: {
data: null,
error: null,
},
pageConfig: {
hasHeader: true,
loader: {
isLoaderActive: true,
message: 'Loading...'
},
alert: {
type: null,
message: null
},
redirect: {
url: '/',
data: null
},
}
};
const newState = {
...state,
pageConfig: {
...state.pageConfig,
loader: {
...state.pageConfig.loader,
isLoaderActive: false
}
}
}
console.log(newState)
或使用Lodash.set
const state = {
auth: {
profile: null,
},
model: {
data: null,
error: null,
},
pageConfig: {
hasHeader: true,
loader: {
isLoaderActive: true,
message: 'Loading...'
},
alert: {
type: null,
message: null
},
redirect: {
url: '/',
data: null
},
}
};
const newState = _.set(state, 'pageConfig.loader.isLoaderActive', false)
console.log(newState)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>