React 钩子useState
用于设置组件状态。但是如何使用钩子来替换回调,如下面的代码:
setState(
{ name: "Michael" },
() => console.log(this.state)
);
我想在状态更新后做点什么。
我知道我可以useEffect
用来做额外的事情,但我必须检查状态先前的值,这需要一些代码。我正在寻找一个可以与useState
钩子一起使用的简单解决方案。
React 钩子useState
用于设置组件状态。但是如何使用钩子来替换回调,如下面的代码:
setState(
{ name: "Michael" },
() => console.log(this.state)
);
我想在状态更新后做点什么。
我知道我可以useEffect
用来做额外的事情,但我必须检查状态先前的值,这需要一些代码。我正在寻找一个可以与useState
钩子一起使用的简单解决方案。
您需要使用useEffect
钩子来实现这一点。
const [counter, setCounter] = useState(0);
const doSomething = () => {
setCounter(123);
}
useEffect(() => {
console.log('Do something after counter has changed', counter);
}, [counter]);
如果你想更新以前的状态,那么你可以在钩子中这样做:
const [count, setCount] = useState(0);
setCount(previousCount => previousCount + 1);
用模拟setState
回调useEffect
,仅在状态更新时触发(不是初始状态):
const [state, setState] = useState({ name: "Michael" })
const isFirstRender = useRef(true)
useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false // toggle flag after first render/mounting
return;
}
console.log(state) // do something after state has updated
}, [state])
useEffectUpdate
function useEffectUpdate(callback) {
const isFirstRender = useRef(true);
useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false; // toggle flag after first render/mounting
return;
}
callback(); // performing action after state has updated
}, [callback]);
}
// client usage, given some state dep
const cb = useCallback(() => { console.log(state) }, [state]); // memoize callback
useEffectUpdate(cb);
useEffect
不是一种直观的方式。我为此创建了一个包装器。在此自定义挂钩中,您可以将回调传输到setState
参数而不是useState
参数。
我刚刚创建了 Typescript 版本。因此,如果您需要在 Javascript 中使用它,只需从代码中删除一些类型符号即可。
const [state, setState] = useStateCallback(1);
setState(2, (n) => {
console.log(n) // 2
});
import { SetStateAction, useCallback, useEffect, useRef, useState } from 'react';
type Callback<T> = (value?: T) => void;
type DispatchWithCallback<T> = (value: T, callback?: Callback<T>) => void;
function useStateCallback<T>(initialState: T | (() => T)): [T, DispatchWithCallback<SetStateAction<T>>] {
const [state, _setState] = useState(initialState);
const callbackRef = useRef<Callback<T>>();
const isFirstCallbackCall = useRef<boolean>(true);
const setState = useCallback((setStateAction: SetStateAction<T>, callback?: Callback<T>): void => {
callbackRef.current = callback;
_setState(setStateAction);
}, []);
useEffect(() => {
if (isFirstCallbackCall.current) {
isFirstCallbackCall.current = false;
return;
}
callbackRef.current?.(state);
}, [state]);
return [state, setState];
}
export default useStateCallback;
如果传递的箭头函数引用了一个变量外部函数,那么它将在状态更新后捕获当前值而不是值。在上面的使用示例中,console.log(state)将打印 1 而不是 2。
我遇到了同样的问题,在我的设置中使用 useEffect 并没有解决问题(我正在从多个子组件的数组中更新父级的状态,我需要知道哪个组件更新了数据)。
将 setState 包装在 Promise 中允许在完成后触发任意操作:
import React, {useState} from 'react'
function App() {
const [count, setCount] = useState(0)
function handleClick(){
Promise.resolve()
.then(() => { setCount(count => count+1)})
.then(() => console.log(count))
}
return (
<button onClick= {handleClick}> Increase counter </button>
)
}
export default App;
以下问题让我朝着正确的方向前进: React 使用钩子时是否会批量更新状态?
setState()
将组件状态的更改排入队列,并告诉 React 该组件及其子组件需要使用更新的状态重新渲染。
setState 方法是异步的,事实上,它不会返回一个 Promise。所以在我们想要更新或调用函数的情况下,该函数可以在 setState 函数中作为第二个参数调用回调。例如,在您上面的例子中,您调用了一个函数作为 setState 回调。
setState(
{ name: "Michael" },
() => console.log(this.state)
);
上面的代码对于类组件可以正常工作,但是在功能组件的情况下,我们不能使用 setState 方法,这我们可以利用使用效果挂钩来达到相同的结果。
想到的显而易见的方法是 ypu 可以与 useEffect 一起使用,如下所示:
const [state, setState] = useState({ name: "Michael" })
useEffect(() => {
console.log(state) // do something after state has updated
}, [state])
但这也会在第一次渲染时触发,因此我们可以更改代码如下,我们可以检查第一次渲染事件并避免状态渲染。因此,可以通过以下方式实现:
我们可以在这里使用用户挂钩来识别第一个渲染。
useRef Hook 允许我们在函数式组件中创建可变变量。它对于访问 DOM 节点/React 元素以及在不触发重新渲染的情况下存储可变变量很有用。
const [state, setState] = useState({ name: "Michael" });
const firstTimeRender = useRef(true);
useEffect(() => {
if (!firstTimeRender.current) {
console.log(state);
}
}, [state])
useEffect(() => {
firstTimeRender.current = false
}, [])
如果有人仍然需要它,我会用 typescript 编写自定义钩子。
import React, { useEffect, useRef, useState } from "react";
export const useStateWithCallback = <T>(initialState: T): [state: T, setState: (updatedState: React.SetStateAction<T>, callback?: (updatedState: T) => void) => void] => {
const [state, setState] = useState<T>(initialState);
const callbackRef = useRef<(updated: T) => void>();
const handleSetState = (updatedState: React.SetStateAction<T>, callback?: (updatedState: T) => void) => {
callbackRef.current = callback;
setState(updatedState);
};
useEffect(() => {
if (typeof callbackRef.current === "function") {
callbackRef.current(state);
callbackRef.current = undefined;
}
}, [state]);
return [state, handleSetState];
}
在你们所有人的帮助下,我能够实现这个自定义钩子:
非常类似于基于类的 this.setState(state, callback)
const useStateWithCallback = (initialState) => {
const [state, setState] = useState(initialState);
const callbackRef = useRef(() => undefined);
const setStateCB = (newState, callback) => {
callbackRef.current = callback;
setState(newState);
};
useEffect(() => {
callbackRef.current?.();
}, [state]);
return [state, setStateCB];
};
这样我们就可以像..
const [isVisible, setIsVisible] = useStateWithCallback(false);
...
setIsVisible(true, () => console.log('callback called now!! =)');
保持冷静和快乐的编码!
您可以使用以下我知道的方式在更新后获取最新状态:
const [state, setState] = useState({name: "Michael"});
const handleChangeName = () => {
setState({name: "Jack"});
}
useEffect(() => {
console.log(state.name); //"Jack"
//do something here
}, [state]);
const [state, setState] = useState({name: "Michael"});
const handleChangeName = () => {
setState({name: "Jack"})
setState(prevState => {
console.log(prevState.name);//"Jack"
//do something here
// return updated state
return prevState;
});
}
const [state, setState] = useState({name: "Michael"});
const stateRef = useRef(state);
stateRef.current = state;
const handleClick = () => {
setState({name: "Jack"});
setTimeout(() => {
//it refers to old state object
console.log(state.name);// "Michael";
//out of syntheticEvent and after batch update
console.log(stateRef.current.name);//"Jack"
//do something here
}, 0);
}
在 react synthesisEvent handler 中,setState 是一个批量更新的过程,所以每次状态的变化都会被等待并返回一个新的状态。
“setState() 并不总是立即更新组件。它可能会批量更新或推迟更新。”,
https://reactjs.org/docs/react-component.html#setstate
这是一个有用的链接
React 是否保持状态更新的顺序?
我有一个用例,我想在设置状态后使用一些参数进行 api 调用。我不想将这些参数设置为我的状态,所以我制作了一个自定义钩子,这是我的解决方案
import { useState, useCallback, useRef, useEffect } from 'react';
import _isFunction from 'lodash/isFunction';
import _noop from 'lodash/noop';
export const useStateWithCallback = initialState => {
const [state, setState] = useState(initialState);
const callbackRef = useRef(_noop);
const handleStateChange = useCallback((updatedState, callback) => {
setState(updatedState);
if (_isFunction(callback)) callbackRef.current = callback;
}, []);
useEffect(() => {
callbackRef.current();
callbackRef.current = _noop; // to clear the callback after it is executed
}, [state]);
return [state, handleStateChange];
};
我们可以编写一个称为useScheduleNextRenderCallback
返回“调度”函数的钩子。在我们调用 之后setState
,我们可以调用“schedule”函数,传递一个我们想要在下一次渲染时运行的回调。
import { useCallback, useEffect, useRef } from "react";
type ScheduledCallback = () => void;
export const useScheduleNextRenderCallback = () => {
const ref = useRef<ScheduledCallback>();
useEffect(() => {
if (ref.current !== undefined) {
ref.current();
ref.current = undefined;
}
});
const schedule = useCallback((fn: ScheduledCallback) => {
ref.current = fn;
}, []);
return schedule;
};
示例用法:
const App = () => {
const scheduleNextRenderCallback = useScheduleNextRenderCallback();
const [state, setState] = useState(0);
const onClick = useCallback(() => {
setState(state => state + 1);
scheduleNextRenderCallback(() => {
console.log("next render");
});
}, []);
return <button onClick={onClick}>click me to update state</button>;
};
您的问题非常有效。让我告诉您 useEffect 默认运行一次,并且每次依赖数组更改后运行一次。
检查下面的例子::
import React,{ useEffect, useState } from "react";
const App = () => {
const [age, setAge] = useState(0);
const [ageFlag, setAgeFlag] = useState(false);
const updateAge = ()=>{
setAgeFlag(false);
setAge(age+1);
setAgeFlag(true);
};
useEffect(() => {
if(!ageFlag){
console.log('effect called without change - by default');
}
else{
console.log('effect called with change ');
}
}, [ageFlag,age]);
return (
<form>
<h2>hooks demo effect.....</h2>
{age}
<button onClick={updateAge}>Text</button>
</form>
);
}
export default App;
如果您希望使用钩子执行 setState 回调,则使用标志变量并在 useEffect 中提供 IF ELSE OR IF 块,以便在满足这些条件时仅执行该代码块。无论何时效果都会随着依赖数组的变化而运行,但效果内部的 IF 代码将仅在特定条件下执行。
简单的解决方案,只需安装
npm 我使用带有回调的状态
import React from 'react';
import { useStateWithCallbackLazy } from "use-state-with-callback";
const initialFilters = {
smart_filter: "",
};
const MyCallBackComp = () => {
const [filters, setFilters] = useStateWithCallbackLazy(initialFilters);
const filterSearchHandle = (e) => {
setFilters(
{
...filters,
smart_filter: e,
},
(value) => console.log("smartFilters:>", value)
);
};
return (
<Input
type="text"
onChange={(e) => filterSearchHandle(e.target.value)}
name="filter"
placeholder="Search any thing..."
/>
);
};
我不认为用 useRef 区分已安装与否是一个好方法,通过确定 useEffect() 中生成的值 useState() 是否是初始值不是更好的方法吗?
const [val, setVal] = useState(null)
useEffect(() => {
if (val === null) return
console.log('not mounted, val updated', val)
}, [val])
useState
和useCallback
:import React, { useCallback, useState } from 'react';
const Test = () => {
const [name, setName] = useState("");
const testCallback = useCallback(() => console.log(name), [name]);
return (
<button onClick={() => {
setName("Michael")
testCallback();
}}>Name</button>
)
};
export default Test;
在我们对 setState 回调有原生内置支持之前,我们可以使用普通的 javascript 方式……调用函数并将新变量直接传递给它。
const [counter, setCounter] = useState(0);
const doSomething = () => {
const newCounter = 123
setCounter(newCounter);
doSomethingWCounter(newCounter);
};
function doSomethingWCounter(newCounter) {
console.log(newCounter); // 123
}
如果您不需要异步更新状态,您可以使用 ref 来保存值,而不是useState
.
const name = useRef("John");
name.current = "Michael";
console.log(name.current); // will print "Michael" since updating the ref is not async
我探索了 use-state-with-callback npm 库和其他类似的自定义钩子,但最后我意识到我可以这样做:
const [user, setUser] = React.useState(
{firstName: 'joe', lastName: 'schmo'}
)
const handleFirstNameChange=(val)=> {
const updatedUser = {
...user,
firstName: val
}
setUser(updatedUser)
updateDatabase(updatedUser)
}
这个怎么样:
const [Name, setName] = useState("");
...
onClick={()=>{
setName("Michael")
setName(prevName=>{...}) //prevName is Michael?
}}
UseEffect 是主要的解决方案。但是正如 Darryl 提到的,使用 useEffect 并传入 state 作为第二个参数有一个缺陷,组件将在初始化过程中运行。如果您只想让回调函数使用更新后的状态值运行,您可以设置一个本地常量并在 setState 和回调中使用它。
const [counter, setCounter] = useState(0);
const doSomething = () => {
const updatedNumber = 123;
setCounter(updatedNumber);
// now you can "do something" with updatedNumber and don't have to worry about the async nature of setState!
console.log(updatedNumber);
}