简体   繁体   English

React 自定义钩子无限循环

[英]React custom hook infinite loop

I tried to make a method using a custom react hook in order to reuse the same state logic in many components, but I got invariant violation "prevent infinite loop".我尝试使用自定义反应钩子制作一种方法,以便在许多组件中重用相同的状态逻辑,但我遇到了不变违规“防止无限循环”。

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

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

usage用法

import useCounter from "./useCounter";

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

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

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

try尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM