React钩子介绍了useState用于设置组件状态的方法。但是我如何使用钩子来代替如下代码的回调:
setState(
{ name: "Michael" },
() => console.log(this.state)
);
Run Code Online (Sandbox Code Playgroud)
我想在状态更新后做一些事情。
我知道我可以useEffect用来做其他事情,但是我必须检查状态以前的值,这需要一个位代码。我正在寻找可以与useState钩子一起使用的简单解决方案。
Bim*_*Grg 40
如果你想更新以前的状态,那么你可以在钩子中这样做:
const [count, setCount] = useState(0);
setCount(previousCount => previousCount + 1);
Run Code Online (Sandbox Code Playgroud)
for*_*d04 34
用 模仿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])
Run Code Online (Sandbox Code Playgroud)
useEffectUpdatefunction 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);
Run Code Online (Sandbox Code Playgroud)
MJ *_*dio 27
useEffect不是一种直观的方式。我为此创建了一个包装器。在这个自定义钩子中,您可以将回调传输到setState参数而不是useState参数。
我刚刚创建了 Typescript 版本。因此,如果您需要在 Javascript 中使用它,只需从代码中删除一些类型符号。
const [state, setState] = useStateCallback(1);
setState(2, (n) => {
console.log(n) // 2
});
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
如果传递的箭头函数引用了一个变量外部函数,那么它将捕获当前值而不是状态更新后的值。在上面的用法示例中,console.log(state)将打印 1 而不是 2。
小智 16
我遇到了同样的问题,在我的设置中使用 useEffect 没有解决问题(我正在从多个子组件的数组中更新父级的状态,我需要知道哪个组件更新了数据)。
在 promise 中包装 setState 允许在完成后触发任意操作:
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;
Run Code Online (Sandbox Code Playgroud)
下面的问题让我找到了正确的方向: 使用钩子时是否 React 批处理状态更新函数?
Zoh*_*jaz 15
您需要使用useEfect钩子来实现
const [counter, setCounter] = useState(0);
const doSomething = () => {
setCounter(123);
}
useEffect(() => {
console.log('Do something after counter has changed', counter);
}, [counter]);
Run Code Online (Sandbox Code Playgroud)
Geo*_*man 15
如果有人仍然需要的话,我用打字稿编写了自定义钩子。
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];
}
Run Code Online (Sandbox Code Playgroud)
Kai*_*Luo 10
您可以使用我知道的以下方法来获取更新后的最新状态:
const [state, setState] = useState({name: "Michael"});
const handleChangeName = () => {
setState({name: "Jack"});
}
useEffect(() => {
console.log(state.name); //"Jack"
//do something here
}, [state]);
Run Code Online (Sandbox Code Playgroud)
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;
});
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
在React SyntheticEvent handler中,setState是一个批量更新的过程,因此每次状态的改变都会被等待并返回一个新的状态。
“setState() 并不总是立即更新组件。它可能会批量或推迟更新,直到稍后。”,https:
//reactjs.org/docs/react-component.html#setstate
这是一个有用的链接
React 是否保持状态更新的顺序?
setState() 将组件状态的更改加入队列,并告诉 React 该组件及其子组件需要使用更新后的状态重新渲染。
setState 方法是异步的,事实上,它不返回承诺。所以在我们想要更新或调用函数的情况下,可以在 setState 函数中调用该函数作为第二个参数的回调。例如,在上面的例子中,你调用了一个函数作为 setState 回调。
setState(
{ name: "Michael" },
() => console.log(this.state)
);
Run Code Online (Sandbox Code Playgroud)
上面的代码对于类组件可以正常工作,但是对于函数组件,我们不能使用 setState 方法,我们可以利用 use effect hook 来达到相同的效果。
显而易见的方法是,ypu 可以与 useEffect 一起使用,如下所示:
const [state, setState] = useState({ name: "Michael" })
useEffect(() => {
console.log(state) // do something after state has updated
}, [state])
Run Code Online (Sandbox Code Playgroud)
但这也会在第一次渲染时触发,因此我们可以更改代码如下,我们可以检查第一个渲染事件并避免状态渲染。因此可以通过以下方式实现:
我们可以在这里使用用户钩子来识别第一次渲染。
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
}, [])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5910 次 |
| 最近记录: |