英文:
how to get the latest updated value from the store while using redux toolkit
问题
I am currently using redux toolkit
and the issue is that even though the value of an item added to the cart of an e-commerce web application is being updated to the redux store, when I try to use useSelector
, it does not find the value of the item added to the cart on the first click. But when I do add the second item, I am able to grab both items from the redux store:
Is there anything that I am missing to solve this issue? Below is my current implementation.
cart.ts
export const cart = createSlice({
name: 'cart',
initialState,
reducers: {
updateByPayload: (state, action: PayloadAction<Cart>) => {
state = merge(state, action.payload);
},
merge
is from lodash
(https://lodash.com/docs/4.17.15#merge)
英文:
I am currently using redux toolkit
and the issue is that even though the value of an item added to the cart of a e-commerce web application is being updated to the redux store, when i try to use useSelector
it does not find the value of the item added to the cart on the first click but when i do add the second item, I am able to grab both items from the redux store:
is there anything that i am missing to solve this issue? below is my current implementation.
cart.ts
export const cart = createSlice({
name: 'cart',
initialState,
reducers: {
updateByPayload: (state, action: PayloadAction<Cart>) => {
state = merge(state, action.payload);
},
merge
is from lodash
(https://lodash.com/docs/4.17.15#merge)
答案1
得分: 1
在Immer支持的reducer中写state = anything
始终是一个错误,并且不起作用。您必须要么修改现有的state
对象,要么返回一个新值。
有关此主题的详细信息,请参阅我们文档中的更长解释:
https://redux-toolkit.js.org/usage/immer-reducers
英文:
Writing state = anything
in an Immer-powered reducer is always a bug, and won't work. You have to either mutate the existing state
object, or return a new value.
See the longer answer on this topic in our docs:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论