reactjs - 在 reducer 中编辑(初始)状态的属性
问题描述
我想更改减速器中我的 initialState 中的数组元素。
我已经读过我应该使用 Object.assign(),然后我只能更改整个数组。
const initState = {
features: [
{id:1, title: 'Information is aviable everywhere', visible:true, status:2, next:2, points: 0},
{id:2, title: 'Information is aviable everywhere v2', visible:false, status:2, next:3, points: 0},
...
这是我目前的做法,但是,它改变了数组顺序......因此以不同的顺序显示:
case 'TEST_FEATURE':
let newFeatures = state.features.filter(feature => {
return action.feature.id !== feature.id && action.feature.next !== feature.id
})
let nexFeature = state.features.find(feature => {
return feature.id === action.feature.next})
nexFeature.visible = true
newFeatures.unshift(nexFeature)
return {
...state,
features: newFeatures
}
我想更改特征 id 2,(仅属性)visibile=true 并具有相同的数组顺序
解决方案
作为一般的经验法则,你不想在你的 reducer 中这样做,因为它应该是纯粹的,但要实现你想要的,你可以这样做:
const newState = state.features.reduce((acc, feature) => {
if(action.feature.id !== feature.id){
feature.visible = !feature.visible;
}
return [ ...acc, feature ];
}, [])
这将保持顺序、更改值、克隆状态并避免您正在执行的其他循环。
推荐阅读
- python - Python ndarray dtype和缓冲区问题 - 它返回不同的值
- python - 如何使用python中的列表有效地对列表进行排序
- c++ - Magick::EnableOpenCL 返回 true 但没有效果
- docker - 一个 docker 容器的多个静态 IP
- python - 使用 Python3 的 SUMIF
- javascript - 未捕获的类型错误:无法读取未定义的属性“图像”(p5.js)
- javascript - 如何在javascript中从另一个对象重组对象
- pattern-matching - 使用什么数据结构来实现模式匹配?
- html - 使用 Bulma 的容器的自动边距
- node.js - 登录后如何存储 JWT 令牌并在标头中传递令牌以通过中间件对其他路由进行身份验证?