我正在编写一个简单的react应用程序,现在我正在处理一个可以接受用户输入的元素。我对onChange()函数中代码行的执行顺序非常好奇。因此,我添加了一条小的print语句来查看事情到底是如何改变的。
这是我的代码
function CreateReview() {
const [input, setInput] = useState({
title:'',
content:''
})
useEffect(() => {
console.log('render');
},[input])
function handleChange(event){
const {name, value} =event.target;
console.log(1)
setInput(prevInput=>
{
console.log(2)
return{
...prevInput, //...prevInput is to reserve the last Input
[name]: value //name is dynamic, "title" then setTitle, "content" then setContent.
}
}
)
console.log(3)
console.log(event.target);
}
function handleClick(event){
event.preventDefault();
console.log(input);
}
return <div className = "container">
<h1>Create Review</h1>
<form>
<div className="form-group">
<input onChange={handleChange} name="title" value={input.title} autoComplete="off" className = 'form-control' placeholder="Your Name"></input>
</div>
<div className="form-group">
<textarea onChange={handleChange} name="content" value={input.content} autoComplete="off" className = 'form-control' placeholder="Review Content"></textarea>
</div>
<button onClick={handleClick} className="btn btn-large btn-info">Add Note</button>
</form>
</div>
}
export default CreateReview;这是输出控制台
我想知道为什么它会变成1,3,2。背后有什么原因吗?
发布于 2021-06-21 10:07:03
有关how state works in react的更多信息,请访问react文档。
因为你关心的useState or setState是异步事件,所以每当你尝试调用它们时,它都会在稍后执行,而不是同步执行(逐行)。
https://stackoverflow.com/questions/68061479
复制相似问题