有人可以从reactjs向我解释一下此代码吗?
谁可以向我解释这个代码吗?我无法像这里发生的事情那样理解。
const cartReducer = (state, action) => {
if (action.type === "ADD") {
const updatedTotalAmount =
state.totalAmount + action.item.price * action.item.amount;
const existingCartItemIndex = state.items.findIndex(
(item) => item.id === action.item.id
);
const existingCartItem = state.items[existingCartItemIndex];
let updatedItems;
if (existingCartItem) {
const updatedItem = {
...existingCartItem,
amount: existingCartItem.amount + action.item.amount,
};
updatedItems = [...state.items];
updatedItems[existingCartItemIndex] = updatedItem;
} else {
updatedItems = state.items.concat(action.item);
}
return {
items: updatedItems,
totalAmount: updatedTotalAmount,
};
}
return defaultCartState;
};
can anyone please explain me this code? I am not able to understand as in what's happening here.
const cartReducer = (state, action) => {
if (action.type === "ADD") {
const updatedTotalAmount =
state.totalAmount + action.item.price * action.item.amount;
const existingCartItemIndex = state.items.findIndex(
(item) => item.id === action.item.id
);
const existingCartItem = state.items[existingCartItemIndex];
let updatedItems;
if (existingCartItem) {
const updatedItem = {
...existingCartItem,
amount: existingCartItem.amount + action.item.amount,
};
updatedItems = [...state.items];
updatedItems[existingCartItemIndex] = updatedItem;
} else {
updatedItems = state.items.concat(action.item);
}
return {
items: updatedItems,
totalAmount: updatedTotalAmount,
};
}
return defaultCartState;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那是一个还原器。请阅读本教程以熟悉其概念:
https://redux.js.js.js.ss.org/tutorials/fundeactals/第三部分 - 态度 - 降低者
That is a redux reducer. Please read this tutorial to get familiar with the concepts of it:
https://redux.js.org/tutorials/fundamentals/part-3-state-actions-reducers
还原器被Redux普及,但不是Redux固有的概念,因为您可以在不从Redux导入的情况下编写还原器。还原器是一种特定函数的概念,即:
来源: redux docs
现在,React与A <代码>用户ducer 挂钩内置。参见钩子API参考。
Reducers were popularized by Redux but are not a concept inherent to Redux in the sense that you can write a reducer without any import from Redux. A reducer is a concept for a particular kind of function i.e.:
Source: Redux docs
React now comes with a
useReducer
hook built-in. See Hooks API Reference.我已经在您的代码中添加了一些评论,希望这使代码更容易理解。
I have added some comments to your code I hope this makes the code a bit more understandable.