【问题标题】:React hook equivalent to callback function after setting state [duplicate]设置状态后反应挂钩相当于回调函数[重复]
【发布时间】:2019-07-20 14:29:53
【问题描述】:

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

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

这与钩子的等价物是什么?

我试过这样做

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

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

但这没有用

有人知道解决办法吗?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

useEffect 挂钩可用于在某些状态更改时调用函数。如果您将 currentRange 作为第二个参数传入数组中,则该函数只会在 currentRange 更改时被调用。

您还可以创建自己的自定义挂钩,使用 useRef 挂钩来跟踪是否是第一次运行效果,这样您就可以跳过第一次调用。

示例

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>

【讨论】:

  • 你能在useEffectSkipFirst中传递多个函数来代替fn吗?那会是什么样子?获取not a function error 以获得额外的参数fn2
  • @RidhwaanShakeel 你可以只传递一个函数,然后调用你的两个函数,例如useEffectSkipFirst(() =&gt; { fn1(); fn2(); }, [currentRange]);
【解决方案2】:

您可以使用 useEffect/useLayoutEffect 来实现:

const SomeComponent = () => {
  const [count, setCount] = React.useState(0)

  React.useEffect(() => {
    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  }, [count]);

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};

如果您正在寻找开箱即用的解决方案,请查看 this custom hook,它的工作方式与 useState 类似,但接受回调函数作为第二个参数:

import useStateWithCallback from 'use-state-with-callback';

const SomeOtherComponent = () => {
  const [count, setCount] = useStateWithCallback(0, count => {
    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  });

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};

可以通过npm install use-state-with-callback安装

【讨论】:

    猜你喜欢
    • 2020-02-22
    • 2020-08-15
    • 2021-10-24
    • 1970-01-01
    • 2021-12-18
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    相关资源
    最近更新 更多