设置状态后反应钩子相当于回调函数 [英] React hook equivalent to callback function after setting state

查看:39
本文介绍了设置状态后反应钩子相当于回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In react (before hooks) when we set state we could call a function after state had been set as such:

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

钩子的等价物是什么?

我试过这样做

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

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

但这没有用

有人知道解决方案吗?

推荐答案

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

The useEffect hook can be used to invoke a function when some state change. If you pass it currentRange in an array as second argument, the function will only be invoked when currentRange change.

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

You can also create your own custom hook that uses the useRef hook to keep track of if it's the first time the effect is being run, so that you can skip the first invocation.

示例

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>

这篇关于设置状态后反应钩子相当于回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆