React useReducer Hook fires twice / how to pass props to reducer?

后端 未结 3 537
-上瘾入骨i
-上瘾入骨i 2020-12-28 17:29

FOREWORD / DESCRIPTION

I am trying to use React\'s new hooks feature for an e-commerce website that I am building, and have been having an issue wor

3条回答
  •  情歌与酒
    2020-12-28 18:05

    An example based on Ryans excellent answer.

      const memoizedReducer = React.useCallback((state, action) => {
        switch (action.type) {
          case "addRow":
            return [...state, 1];
          case "deleteRow":
            return [];
          default:
            throw new Error();
        }
      }, []) // <--- if you have vars/deps inside the reducer that changes, they need to go here
    
      const [data, dispatch] = React.useReducer(memoizedReducer, _data);
    
    

提交回复
热议问题