在反应中(在钩子之前),当我们设置状态时,我们可以在状态设置为这样后调用一个函数:
this.setState({}, () => {//Callback})
钩子相当于什么?
我尝试这样做
const [currentRange, setCurrentRange] = useState("24h"); setCurrentRange(someRange, () => console.log('hi'))
但这没有用
有人知道解决方案吗?
useEffect当某些状态改变时,该钩子可以用来调用一个函数。如果将其currentRange作为第二个参数传递到数组中,则仅在currentRange更改时才调用该函数。
useEffect
currentRange
您还可以创建自己的自定义钩子,使用该useRef钩子来跟踪效果是否是第一次运行,从而可以跳过第一次调用。
useRef
例
const { useRef, useState, useEffect } = React; function useEffectSkipFirst(fn, arr) { const isFirst = useRef(true); useEffect(() => { if (isFirst.current) { isFirst.current = false; 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>