【发布时间】:2020-04-11 17:35:38
【问题描述】:
export default function Example() {
useEffect(()=>{
console.log('DOM has not rendered anything yet')
});
return (
<div>
Hello
</div>
);
}
上面的代码首先是控制台消息,然后Hello 出现在我的页面上。但是,通过调试代码,我可以看到return 在useEffect 之前。那么为什么useEffect第一次运行时看不到Hello呢?
此外,如果使用来自https://reactjs.org/docs/hooks-effect.html#example-using-hooks的代码:
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
看到第一次执行useEffect的回调时,只有按钮可见,You clicked 0 times不可见。
【问题讨论】:
-
useEffect和传递给它的回调是两个不同的东西。 -
在显示 hello 之前打印控制台是什么意思?你真的能看到两件事发生之间的一毫秒吗?我在效果中添加了
debugger,当效果执行时,我可以看到 dom 中打印的 hello,因此即使您有毫秒级的快速视力,调试器也会证明您错了。 -
通过调试代码可以看到回调执行时页面是空的。
-
不,不是。不是您提供的代码。当调试器在效果中暂停时,我可以在 dom 中看到 hello。
标签: reactjs react-hooks