我试图使用自定义的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>;
}
答案 0 :(得分:3)
尝试
return {
increase: () => setCounter(count + 1),
decrease: () => setCounter(count - 1),
...
};