我有一个组件,想要在提交表单后显示另一个组件。
当我在表单提交上运行函数时,我将提交的值更改为true
,如果我执行了console.log(submitted)
,它将更改为true
,但是在模板中它仍然为false,因此Alert
组件未显示。
我正在尝试学习钩子,也许是我如何使用钩子的问题?
我的组件看起来像这样
export const SignupForm = () => {
let name:any = handleUserInput('');
let email:any = handleUserInput('');
let password:any = handleUserInput('');
let submitted:any = false;
function registerUser(event: React.FormEvent<HTMLFormElement>): void {
event.preventDefault();
submitted = true;
const registerInfo = Object.assign({}, {
email: email.value,
password: password.value,
name: name.value
});
axios.post('/register', registerInfo)
.then(response => {
errors = response.data.errors
})
.catch(error => console.log(error))
}
function handleUserInput(initialValue: string): object {
const [value, setValue] = useState(initialValue);
function handleChange(event: Event): void {
let element = event.target as HTMLInputElement;
setValue(element.value);
}
return {
value,
onChange: handleChange
}
}
return (
<div>
<div dangerouslySetInnerHTML={{__html: submitted}}></div>
{submitted ? <Alert /> : ''}
<div className="form-holder">
<form action="POST" className="form" onSubmit={(e) => registerUser(e)}>
<label htmlFor="Email">Email</label>
<input type="text" id="email" className="form__input" {...email} required />
<label htmlFor="password">Password</label>
<input type="password" id="password" className="form__input" {...password} required />
<label htmlFor="name">Name</label>
<input type="text" id="name" className="form__input" {...name} required />
<button type="submit" className="form__button">Signup</button>
</form>
</div>
</div>
);
}
答案 0 :(得分:1)
submitted
局部变量是异步分配的。这不会导致组件更新。
应该是:
...
const [submitted, setSubmitted] = useState(false);
function registerUser(event: React.FormEvent<HTMLFormElement>): void {
event.preventDefault();
setSubmitted(true);
...