【问题标题】:A mistake causes the function to be rendered infinity一个错误导致函数被渲染为无穷大
【发布时间】: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


    【解决方案1】:

    你必须给你的 onClick 添加一个回调:

    onClick={() => selectItem(selected[0].key)}
    

    否则,将在每次渲染时调用 selectItem,从而导致渲染的无限循环。和 useReducer 无关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 2012-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多