对于articleFetched操作,我将获得如下所示的数组有效载荷,我如何将来自有效载荷的id提取/分配到ids state字段中,并为state.data分配整个对象?
const payload =
[
{ id: 1,
items: 4
color: ['green', 'blue']
},
{ id: 2,
items: 10
color: ['yellow', 'red']
}
]
export const articlesSlice = createSlice({
name: 'articles',
initialState,
reducers: {
startFetching: (state) => {
state.loading = true
},
articlesFetched: (state, action) => {
state.loading = false
state.ids = ??
state.data = ??
},
},
});
如果我读得正确,你应该能够做一些事情,比如:
export const articlesSlice = createSlice({
name: 'articles',
initialState,
reducers: {
startFetching: (state) => {
state.loading = true
},
articlesFetched: (state, action) => {
state.loading = false
state.ids = action.payload.reduce((acc, item) => {
return [...acc, item.id]
}, [])
state.data = action.payload.reduce((acc, item) => {
return [...acc, ...item.color]
}, [])
},
},
});
嘿,我认为你没有正确更新状态,你不应该将值分配给当前状态,因为你需要返回更新状态的新副本,而不改变原始状态,你可以使用这样的映射函数来完成你想要的。
export const articlesSlice = createSlice({
name: 'articles',
initialState,
reducers: {
startFetching: (state) => {
return {
...state,
loading: true,
}
},
articlesFetched: (state, action) => {
// Array with the ids
const ids = action.payload.map(({id}) => id)
// The whole array with the objects
const data = action.payload
return {
...state,
loading: false,
ids,
data,
}
},
},
});