在类组件中,我能够做这样的事情:
this.setState({loading: true}, () => console.log('state updated'));
使用 useState 的功能组件中的等效项是什么?
如果你有其他逻辑要在设置状态后执行,这些逻辑通常会包装在特定于正在执行的操作的处理程序函数中:
import React, { useState } from 'react'
const Component = () => {
const [loading, setLoading] = useState(false)
const handleLoading = () => {
setLoading(true);
console.log('state updated');
}
return <button onClick={handleLoading}>Click Me</button>;
}
注意:如下@Federkun说明,这不会为您提供刚刚设置的状态,因为组件尚未重新渲染。
我假设你可以为此目的从useEffect钩子中受益。下面,你可以从官方 React 手册中找到一个例子。
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
发现正确的方法是使用前面提到的useEffect钩子,然后将我们正在侦听的状态作为参数传递(在本例中为计数(
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
function onCountChange(){
console.log('count has changed to', count);
}
// this will run every time count changes,
useEffect(() => {
// function that we want to run on ever change of count
onCountChange()
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}