首页 > 解决方案 > 在 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 并具有相同的数组顺序

标签: reactjsredux

解决方案


作为一般的经验法则,你不想在你的 reducer 中这样做,因为它应该是纯粹的,但要实现你想要的,你可以这样做:

const newState = state.features.reduce((acc, feature) => {
    if(action.feature.id !== feature.id){
        feature.visible = !feature.visible;
    }
    return [ ...acc, feature ];
}, [])

这将保持顺序、更改值、克隆状态并避免您正在执行的其他循环。


推荐阅读