Redux 工具包减速器未接收({action.payload})
Redux toolkit reducer not receiving ( {action.payload} )
我正在尝试在每次点击时自定义服务器端分页。但是当我尝试使用 reducer 更新状态时,出现了这个错误
我发送这个减速器的组件文件
function changePageByNumber(page){
dispatch(pageByNumber({page:page})) //dispatching reducer
dispatch(fetchUsers({page:page}));
}
切片文件
const usersSlice = createSlice({
name:'users',
initialState: usersAdapter.getInitialState( { loading: false, page: 1, total_pages: null } ),
reducers:{
pageByNumber: (state,{action}) => {
state.page = action.payload // why action not getting payload
}
},
extraReducers: {
[fetchUsers.pending]: (state) => {
state.loading = true
},
[fetchUsers.fulfilled]: (state, { payload}) => {
state.loading = false,
state.total_records = payload.total,
state.per_page = payload.per_page,
state.total_pages = payload.total/payload.per_page,
usersAdapter.setAll(state, payload.data)
},
[fetchUsers.rejected]: (state) => {
state.loading = false
}
},
});
export const usersSelectors = usersAdapter.getSelectors(
(state) => state.users,
)
export const {pageByNumber} = usersSlice.actions
export default usersSlice.reducer
动作对象是传递给reducer的第二个参数。没有 action.action
,因此尝试访问 action.action.payload
会引发错误。
你应该从 action
:
解构 payload
属性
pageByNumber: (state, action) => {
state.page = action.payload;
}
或
pageByNumber: (state, { payload }) => {
state.page = payload;
}
根据调度的动作 dispatch(pageByNumber({ page: page }))
我还要说你需要访问动作负载的 page
属性:
pageByNumber: (state, action) => {
state.page = action.payload.page;
}
我正在尝试在每次点击时自定义服务器端分页。但是当我尝试使用 reducer 更新状态时,出现了这个错误
我发送这个减速器的组件文件
function changePageByNumber(page){
dispatch(pageByNumber({page:page})) //dispatching reducer
dispatch(fetchUsers({page:page}));
}
切片文件
const usersSlice = createSlice({
name:'users',
initialState: usersAdapter.getInitialState( { loading: false, page: 1, total_pages: null } ),
reducers:{
pageByNumber: (state,{action}) => {
state.page = action.payload // why action not getting payload
}
},
extraReducers: {
[fetchUsers.pending]: (state) => {
state.loading = true
},
[fetchUsers.fulfilled]: (state, { payload}) => {
state.loading = false,
state.total_records = payload.total,
state.per_page = payload.per_page,
state.total_pages = payload.total/payload.per_page,
usersAdapter.setAll(state, payload.data)
},
[fetchUsers.rejected]: (state) => {
state.loading = false
}
},
});
export const usersSelectors = usersAdapter.getSelectors(
(state) => state.users,
)
export const {pageByNumber} = usersSlice.actions
export default usersSlice.reducer
动作对象是传递给reducer的第二个参数。没有 action.action
,因此尝试访问 action.action.payload
会引发错误。
你应该从 action
:
payload
属性
pageByNumber: (state, action) => {
state.page = action.payload;
}
或
pageByNumber: (state, { payload }) => {
state.page = payload;
}
根据调度的动作 dispatch(pageByNumber({ page: page }))
我还要说你需要访问动作负载的 page
属性:
pageByNumber: (state, action) => {
state.page = action.payload.page;
}