使用 useState 后控制台记录状态不返回当前值
使用 console.log()
在使用 reactjs useState()
钩子后,没有返回该状态的当前值,我该如何处理?
using console.log()
after using reactjs useState()
hook, doesn't return the current value of this state, How can I handle this?
这是案例的代码,试着弄清楚控制台日志显示的是什么.
Here's code for the case, try to figure out what's the console log display.
import React, { useState } from "react";
import ReactDOM from "react-dom";
function Weather() {
const [weather, setWeather] = useState();
return (
<input
value={weather}
onChange={(e) => {
setWeather(e.target.value);
console.log(weather);
}}
/>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Weather />, rootElement);
推荐答案
useState
默认情况下只做一件事,只做一件事,设置新状态并重新渲染函数.它本质上是异步的,因此默认情况下,通常在它运行之后运行的方法.
useState
by default simply does one thing and one thing only, set the new state and cause a re-render of the function. It is asynchronous in nature so by default, methods running after it usually run.
在您的示例中,在新加载页面时,键入s"会导致 useState 更改状态,但由于它是异步的,因此将使用旧状态值调用 console.log
, 即 undefined
(因为你没有设置一个值.你应该考虑设置一个初始状态,如果你想)
From your example, on a fresh load of the page, typing 's' causes useState to change the state, but because it is asynchronous, console.log
will be called with the old state value, i.e. undefined
(since you didn't set a value. You should consider setting an initial state, if you want to)
const [weather, setWeather] = useState(''); // Set the intial state
真正读取状态值的唯一方法是使用useEffect
,它在组件重新渲染时调用.你的方法就变成了:
The only way to truly read the value of the state is to use useEffect
, which is called when there is a re-render of the component. Your method simply becomes:
import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
function Weather() {
const [weather, setWeather] = useState('');
useEffect(() => console.log(weather), [weather]);
const changeValue = event => setWeather(event.target.value);
return <input value={weather} onChange={changeValue} />;
}
const rootElement = document.getElementById('root');
ReactDOM.render(<Weather />, rootElement);
相关文章