反应自定义钩子无限循环

时间:2019-12-03 04:05:33

标签: javascript reactjs ecmascript-6

我试图使用自定义的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

1 个答案:

答案 0 :(得分:3)

尝试

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