在反应中(在钩子(Hook)之前),当我们设置状态时,我们可以在状态被设置为这样后调用一个函数:

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

钩子(Hook)相当于什么?

我尝试这样做
const [currentRange, setCurrentRange] = useState("24h");

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


但这没有用

有人知道解决方案吗?

最佳答案

当状态发生某些变化时, useEffect 挂钩可用于调用函数。如果在数组中将currentRange作为第二个参数传递,则仅当currentRange更改时才调用该函数。
您还可以创建自己的自定义钩子(Hook),该钩子(Hook)使用 useRef 钩子(Hook)来跟踪效果是否是第一次运行,以便您可以跳过第一次调用。
示例

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>

关于javascript - 设置状态后 react Hook 相当于回调函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54895801/

10-16 00:35