How can I return immutable data from redux reducer?

时光总嘲笑我的痴心妄想 提交于 2021-01-29 06:12:56

问题


For a learning and test project, I'm trying to return immutable redux data from reducer because safe data for component. this is my reducer code :

function itemsReducer(state = [], action) {
    switch(action.type) {
        case 'ITEMS':
            return [...action.data]
        default:
            return state
    }
}

And this is my loop code :

<ul>
    {
        this.props.items.map((item) => (
            <li>{item.name.first} {item.name.last}</li>
        ))
    }
</ul>

now every things work right, but after change on props with this method :

change() {
    this.props.items[0] = 'empty'
}

and after loading again items I have this error :

TypeError: Cannot read property 'first' of undefined

Apparently the items did not copy with spread syntax in my reducer and all changes override on that. after executing the data load action at all the index #0 is 'empty'

Thank you


回答1:


You shouldn't be mutating the props directly in component, instead dispatch an action that updates the result in reducer

change() {
    this.props.updateItem({first: 'empty'}, 0);
}

and action creator would be

const updateItem = (item, index) => {
   return {type: 'UPDATE_ITEM', item, index}
}

and reducer

function itemsReducer(state = [], action) {
    switch(action.type) {
        case 'ITEMS':
            return [...action.data]
        case 'UPDATE_ITEM': 
            return [...state.slice(0, action.index), {...state[index], ...action.item}, ...state.slice(index+1)];
        default:
            return state
    }
}


来源:https://stackoverflow.com/questions/55511749/how-can-i-return-immutable-data-from-redux-reducer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!