英文:
Why is UseEffect not getting the updated value of my state variable in ReactJS?
问题
I am new to React and have a hard time understanding why when I call useEffect after I just set the new state on a variable, the new value is undefined. Can someone also explain why the second UseEffect hook is called twice. Is it because it's called on initial mount, and then called when it finally changes state from the first useEffect? How can I get it to fire only once val has a defined value that was set in the first useEffect?
import React from 'react';
import { useState, useEffect } from 'react';
export function App(props) {
const [val, setVal] = useState();
useEffect(() => {
setVal("hello");
}, []);
useEffect(() => {
console.log("value: ", val);
}, [val])
return (
<div className='App'>
</div>
);
}
英文:
I am new to React and have a hard time understanding why when I call useEffect after I just set the new state on a variable, the new value is undefined. Can someone also explain why the second UseEffect hook is called twice. Is it because it's called on initial mount, and then called when it finally changes state from the first useEffect? How can I get it to fire only once val has a defined value that was set in the first useEffect?
import React from 'react';
import {useState, useEffect} from 'react'
export function App(props) {
const [val, setVal] = useState();
useEffect(() => {
setVal("hello");
},[]);
useEffect(() => {
console.log("value: ", val);
}, [val])
return (
<div className='App'>
</div>
);
}
答案1
得分: 1
The code is working exactly as I'd expect it to.
在第一次渲染后(更具体地说,就在渲染之后立即),两个效果都会执行。它们分别:
- 排队进行状态更新
- 在控制台记录
undefined
然后,当状态更新时,组件重新渲染。这次重新渲染对于val
来说有一个新的状态值,触发了第二个useEffect
的执行。它:
- 在控制台记录
"hello"
> 如何使它在val
具有在第一个useEffect
中设置的已定义值时才触发?
如果你希望某些事情在特定条件下发生,你可以使用if
语句。例如:
useEffect(() => {
if (val) {
console.log("value: ", val);
}
}, [val])
只有在val
有一个“真值”时,它才会将val
记录到控制台。
英文:
The code is working exactly as I'd expect it to.
On (or more specifically, immediately after) the first render, both effects execute. Which:
- queues a state update and
- logs
undefined
to the console
Then when state is updated, the component re-renders. This re-render has a new state value for val
, which triggers the second useEffect
to execute. Which:
- logs
"hello"
to the console
> How can I get it to fire only once val has a defined value that was set in the first useEffect?
If you want something to happen conditionally, you'd use an if
statement. For example:
useEffect(() => {
if (val) {
console.log("value: ", val);
}
}, [val])
This will only log val
to the console if it has a "truthy" value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论