如何 edit/update slice redux 中的 initialState

how to edit/update initialState in slice redux

您好,我正在开发一个公告应用程序,我需要更新或编辑其中一个公告。卡在这了,不知道怎么解决。

const announcements = createSlice({
    name: 'announcements',
    initialState: {
        announcements: [
            {id: 1, title: 'dog', description: 'dog eat apple', dateAdded: '21.10.1120'},
            {id: 2, title: 'cat', description: 'cat eat meat', dateAdded: '11.1.2020'},
            {id: 3, title: 'monkey', description: 'monkey eat banana', dateAdded: '11.5.2021'},
        ],
    },
    reducers: {
        addAnnouncement: (state, action) => {
            state.announcements = [...state.announcements, action.payload];
        },
        deleteAnnouncement: (state, action) => {
            state.announcements = state.announcements.filter(announcement => announcement.id !== action.payload.id);
        },
        editAnnouncement: (state, action) => {
            const {description, title, id, dateAdded} = action.payload;
            state.announcements = state.announcements.find(announcement => announcement.id === id

        }
    }
})
````

如果您的数据结构不同,会更容易、更高效

const announcements = createSlice({
        name: 'announcements',
        initialState: {
            announcementsById: {
                1: {id: 1, title: 'dog', description: 'dog eat apple', dateAdded: '21.10.1120'},
                2: {id: 2, title: 'cat', description: 'cat eat meat', dateAdded: '11.1.2020'},
                3: {id: 3, title: 'monkey', description: 'monkey eat banana', dateAdded: '11.5.2021'},
            },
        },
        reducers: {

            editAnnouncement: (state, action) => {
               state.announcementsById[action.payload.id] = action.payload
    
            }
        }
    })

看看这个文档:https://redux.js.org/usage/structuring-reducers/normalizing-state-shape