React hook 相当于设置状态后的回调函数[重复]

2024-01-03

在反应中(在钩子之前),当我们设置状态时,我们可以在状态设置后调用一个函数,如下所示:

this.setState({}, () => {//Callback})

这对于钩子来说相当于什么?

我尝试这样做

const [currentRange, setCurrentRange] = useState("24h");

setCurrentRange(someRange, () => console.log('hi')) 

但这没有用

有人知道这个问题的解决方案吗?


The useEffect https://reactjs.org/docs/hooks-reference.html#useeffect钩子可用于在某些状态发生变化时调用函数。如果你通过了currentRange在数组中作为第二个参数,该函数仅在以下情况下才会被调用currentRange change.

您还可以创建自己的自定义挂钩,使用useRef https://reactjs.org/docs/hooks-reference.html#useref挂钩来跟踪效果是否是第一次运行,以便您可以跳过第一次调用。

Example

const { useRef, useState, useEffect } = React;

function useEffectSkipFirst(fn, arr) {
  const isFirst = useRef(true);

  useEffect(() => {
    if (isFirst.current) {
      isFirst.current = false;
      return;
    }

    return fn();
  }, arr);
}

function App() {
  const [currentRange, setCurrentRange] = useState("24h");

  useEffectSkipFirst(
    () => {
      console.log("hi");
    },
    [currentRange]
  );

  return (
    <button
      onClick={() => setCurrentRange(Math.floor(Math.random() * 24) + 1 + "h")}
    >
      Change range ({currentRange})
    </button>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React hook 相当于设置状态后的回调函数[重复] 的相关文章

随机推荐