gpt4 book ai didi

reactjs - React useEffect 钩子(Hook)是否保证按顺序执行?

转载 作者:行者123 更新时间:2023-12-04 13:10:36 25 4
gpt4 key购买 nike

假设我有这个:

function Example(props) {
const { prop1, prop2 } = props;
const latestProp1 = useRef(prop1);

useEffect(() => {
latestProp1.current = prop1;
}, [prop1]);

useEffect(() => {
console.log(latestProp1.current);
}, [prop2]);

return null;
}
如果两者都 prop1prop2在相同的重新渲染中更改,是否保证控制台会记录新的 prop1值(value)?
如果我交换 useEffect 钩子(Hook)的位置 -
  useEffect(() => {
console.log(latestProp1.current);
}, [prop2]);

useEffect(() => {
latestProp1.current = prop1;
}, [prop1]);
是否可以保证控制台会记录旧的 prop1值(从渲染之前)?

最佳答案

是的,如果您关注 Rules of Hooks ,确保调用顺序(通过数组索引调用钩子(Hook),检查钩子(Hook)是如何实现的)。

By following this rule, you ensure that Hooks are called in the same order each time a component renders.


因此,通过模拟 batched set state ( prop1prop2 在相同的重新渲染中发生变化)您可以注意到 first将始终记录在 second 之前:
function Example(props) {
const { prop1, prop2 } = props;

React.useEffect(() => {
console.log("first");
}, [prop1]);

React.useEffect(() => {
console.log("second");
}, [prop2]);

return <>Example</>;
}

function Component() {
const [counter, setCounter] = React.useState(0);
const [counter2, setCounter2] = React.useState(0);

const together = () => {
setCounter2((p) => p + 1);
setCounter((p) => p + 1);
};

return (
<>
<Example prop1={counter} prop2={counter2} />
<button onClick={together}>together</button>
</>
);
}
Edit Example Batching Call Order

关于reactjs - React useEffect 钩子(Hook)是否保证按顺序执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65721515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com