State React,为什么变化不快
State React, why it doesn't change fast
问题是,为什么当我们在textarea中输入“1”时console.log显示的是空字符串,但实际上是textInput = “1”?
const [textInput, setTextInput] = useState('')
const inputAction= (e) => {
setTextInput(e.target.value);
console.log(textInput);
};
<textarea
value={textInput}
onChange={inputAction}
></textarea>
setTextInput
不会立即更新 textInput
的值 - 相反,它会排队重新渲染,并在渲染期间更新该值。这是一个非常常见的 React 问题,我鼓励您继续阅读 State and Lifecycle 以更好地了解这里发生的事情。
问题是,为什么当我们在textarea中输入“1”时console.log显示的是空字符串,但实际上是textInput = “1”?
const [textInput, setTextInput] = useState('')
const inputAction= (e) => {
setTextInput(e.target.value);
console.log(textInput);
};
<textarea
value={textInput}
onChange={inputAction}
></textarea>
setTextInput
不会立即更新 textInput
的值 - 相反,它会排队重新渲染,并在渲染期间更新该值。这是一个非常常见的 React 问题,我鼓励您继续阅读 State and Lifecycle 以更好地了解这里发生的事情。