[英]useState is not updating the state in React
ChangeHandler
updates the state fine. ChangeHandler
更新状态很好。
However, updating the state of id
on onSubmit
does not seem to update the id.但是,在onSubmit
上更新id
的状态似乎并没有更新 id。
Code is :代码是:
import { useState } from "react"
export default function Form(props) {
const [userInput, setUserInput] = useState({
name: "",
url: "",
id: ""
})
const ChangeHandler = (e) => {
const { name, value } = e.target
setUserInput((prevState) => {
return {
...prevState,
[name]: value
}
})
}
const clearForm = () => {
setUserInput({
name: "",
url: "",
id: ""
})
}
const onSubmit = (e) => {
e.preventDefault()
setUserInput(prevState => {
return {
...prevState,
id: Math.floor(Math.random() * 100)
} //does not work?
});
props.onFormData(userInput)
clearForm()
}
return (
<div>
<form onSubmit={onSubmit}>
<input name="name" className="input" type="text" value={userInput.name} placeholder="Name" onChange={ChangeHandler}></input>
<input name="url" className="input" type="text" value={userInput.url} placeholder="url" onChange={ChangeHandler}></input>
<button type="submit" className="button is-primary" >Send</button>
</form>
</div>
)
}
You don't need to use setUserInput
.您不需要使用setUserInput
。 Just sand parms like this:只是像这样的沙子:
props.onFormData({
...userInput,
id: Math.floor(Math.random() * 100)
})
When use change state, the state will applies on next render.使用更改状态时,该状态将应用于下一次渲染。 That's why you can't use updated state.这就是为什么你不能使用更新的状态。
When you do当你这样做
setUserInput((prevState) => {
return {
...prevState,
id: Math.floor(Math.random() * 100),
};
});
props.onFormData(userInput);
userInput
will not have updated to the new value you set yet. userInput
不会更新为您设置的新值。 The new value will be available on the next render, until then userInput
will still give you the old value.新值将在下一次渲染时可用,在此之前userInput
仍会为您提供旧值。 If it helps, you can think of setUserInput()
as a deferred function that will resolve the update later.如果有帮助,您可以将setUserInput()
视为延迟函数,稍后将解决更新。
You can sidestep the problem by putting your new state in a temporary variable which you can use for both purposes.您可以通过将新状态放入可用于这两种目的的临时变量来回避问题。
const newUserInput = {
...userInput,
id: Math.floor(Math.random() * 100),
};
setUserInput(newUserInput);
props.onFormData(newUserInput);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.