第一个问题:
useEffect
在组件完全渲染后运行,并且不会阻止浏览器的绘制。考虑这个例子:
export default function App() {
console.log("I am code from the app")
React.useEffect(() => {
console.log("I am the effect")
})
React.useLayoutEffect(() => {
console.log("I am the layout effect")
})
return (
<div className="App">
{console.log("I am inside the jsx")}
<h1>Hello World</h1>
</div>
);
}
将输出:
I am code from the app
I am inside the jsx
I am the layout effect
I am the effect
所以
使用效果
回调将作为最后一件事发生,在所有其他事情都完成之后。
第二个问题:
你只能通过使用
useState
在效果中设置状态:
const [data, setData] = React.useState()
React.useEffect(() => {
// Your other code
const processedData = processeData(data);
setData(processedData)
}, [setData])