为了在许多组件中重用相同的状态逻辑,我尝试使用自定义的React钩子来创建方法,但是我遇到了不变的冲突“ prevent infinite loop”。

function useCounter(initial) {
  const [count, setCounter] = useState(initial);

  return {
    increase: setCounter(count + 1),
    decrease: setCounter(count - 1),
    count
  };
}


用法

import useCounter from "./useCounter";

function CompOne() {
  const { count, increase } = useCounter(0);

  return <div onClick={() => increase()}>Component {count}</div>;
}


演示https://codesandbox.io/s/practical-hooks-440l1

最佳答案

尝试

  return {
    increase: () => setCounter(count + 1),
    decrease: () => setCounter(count - 1),
    ...
  };

10-07 14:48