如何在使用Redux Toolkit时获取存储中的最新更新值

huangapple go评论63阅读模式
英文:

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: &#39;cart&#39;,
  initialState,
  reducers: {
    updateByPayload: (state, action: PayloadAction&lt;Cart&gt;) =&gt; {
      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:

https://redux-toolkit.js.org/usage/immer-reducers

huangapple
  • 本文由 发表于 2023年2月14日 05:01:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75441146.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定