【发布时间】:2020-06-07 00:20:27
【问题描述】:
我知道反应组状态会更新以提高性能,但我需要获取当前状态,请告诉我该怎么做?
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [inputValue, setInputValue] = useState("");
const handleChange = e => {
console.log(e.target.value, 'here is the desired state');
setInputValue(e.target.value,'but here is always one step behind');
console.log(inputValue); // I am outputting the log from the handler and this is not true. The state has changed and there is no error.
};
return (
<div className="App">
<input type="text" value={inputValue} onChange={handleChange} />
</div>
);
}
https://codesandbox.io/s/react-onchange-3pond?file=/src/App.js:0-407
【问题讨论】:
-
不使用onchange?改为听向上或向下键?
-
setInputValue()是异步的,因为所有状态设置都在 React 中。您可以使用useEffect()跟踪更改 -
@evolutionxbox 我需要一个受控组件,向上或向下键不会改变输入值
-
什么落后了一步?
-
当前状态 -
inputValuedropbox.com/s/72f28hppiu1k4oy/…
标签: javascript reactjs setstate