错误导致函数呈现无穷大
A mistake causes the function to be rendered infinity
我试图在我的代码中添加一个按钮,通过单击它来更改数组的某些属性。为此,我使用了 Context 和 Reducer。但有个问题!
当我评论调度时,问题就解决了,函数只渲染一次。但是当我使用 Reducer 时,该函数会无限次渲染!请帮我 :(
值得一提的是,这个reducer已经在其他组件中使用过,但是没有出现过这个问题
App.js : (only reducer)
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},
]
});
Cart.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]
};
};
您必须向您的 onClick 添加回调:
onClick={() => selectItem(selected[0].key)}
否则将在每次渲染时调用 selectItem,从而导致渲染的无限循环。与useReducer无关。
我试图在我的代码中添加一个按钮,通过单击它来更改数组的某些属性。为此,我使用了 Context 和 Reducer。但有个问题! 当我评论调度时,问题就解决了,函数只渲染一次。但是当我使用 Reducer 时,该函数会无限次渲染!请帮我 :( 值得一提的是,这个reducer已经在其他组件中使用过,但是没有出现过这个问题
App.js : (only reducer)
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},
]
});
Cart.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]
};
};
您必须向您的 onClick 添加回调:
onClick={() => selectItem(selected[0].key)}
否则将在每次渲染时调用 selectItem,从而导致渲染的无限循环。与useReducer无关。