【发布时间】:2021-10-17 08:44:33
【问题描述】:
我尝试在我的代码中添加一个按钮,通过单击它来更改数组的某些属性。为此,我使用了 Context 和 Reducer。但有个问题! 当我评论调度时,问题就解决了,函数只渲染一次。但是当我使用 Reducer 时,该函数会无限次渲染!请帮我 :( 值得一提的是,这个reducer已经在其他组件中使用过,但是没有出现这个问题。
App.js :(仅减速器)
const [goodsState, goodsDispatch] = useReducer(GoodsReducer, {
goods: [
{name : 'x', price : 126000, selected : false, key : 1},
{name : 'y', price : 123000, selected : false, key : 2},
{name : 'z', price : 126000, selected : false, key : 3},
]
});
购物车.js:
import React, { useContext } from "react";
import GoodsContext from "../Contexts/GoodsContext";
export default function Cart(){
const goodsContext = useContext(GoodsContext);
const selectItem = (key) => {
goodsContext.goodsDispatch({ type: "buy-item", payload: { key: key } });
};
return (
<div>
<h1>{selected[0].name}</h1>
<h1>{selected[0].price}</h1>
<button onClick={selectItem(selected[0].key)}>+</button>
//some cod
</div>
);
};
GoodsReducer.js :
export default function GoodsReducer(state, action) {
switch (action.type) {
case "buy-item":
return buyItem(state, action);
default:
return state;
}
}
const buyItem = (state, action) => {
let key = action.payload.key;
changedGoods.selected = true;
const otherGoods = state.goods.filter((good) => good.key !== key);
return {
...state,
goods: [...otherGoods, changedGoods]
};
};
【问题讨论】:
标签: reactjs react-hooks use-effect reducers use-context