我正在尝试使用带有React 16.7.0-alpha.2的useState钩子,将在udemy课程中看到的示例从基于类的有状态组件改编为基于函数的组件
虽然原始数据类型的setter函数可以正常工作(例如setUsername),但是为数组变量调用setter无效/结果。至少它不会将状态变量重置为空数组。
另一方面,使用concat方法从状态设置阵列的新副本会按预期工作。
我还是React钩子的新手,想知道我错过了什么?
import React, {useState} from 'react';
import { Grid, Form, Segment, Button, Header, Message, Icon } from 'semantic-ui-react';
import { Link } from 'react-router-dom';
import { registerUser } from './authFunctions';
import { isRegisterFormEmpty } from './validatorFunctions';
const Register = () => {
//defining state properties and setters:
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [passwordConfirmation, setPasswordConfirmation] = useState('');
const [registerErrors, setRegisterErrors] = useState([]);
//defining handlers:
const onUsernameChange = e => setUsername(e.target.value);
const onEmailChange = e => setEmail(e.target.value);
const onPasswordChange = e => setPassword(e.target.value);
const onPasswordConfirmationChange = e => setPasswordConfirmation(e.target.value);
const onFormSubmit = e => {
e.preventDefault(); //prevent a page reload
//set registerErrors to empty array in case that the user clicks on submit again
setRegisterErrors([]); // DOES NOT WORK
setUsername('JDoe'); //works as expected
if( isRegisterFormEmpty(username, email, password, passwordConfirmation) ) {
let error = {message: 'Please fill in all fields'};
setRegisterErrors( registerErrors.concat(error) ); //THIS WORKS FINE, THOUGH...
} else {
//registerUser(username, email, password, passwordConfirmation);
}//if
}//onFormSubmit
const showErrors = () => registerErrors.map( (error, idx) => <p key={idx}>{error.message}</p> );
return (
<Grid textAlign='center' verticalAlign='middle' className='app'>
<Grid.Column style={{ maxWidth: 450 }}>
<Header as='h2' icon color='teal' textAlign='center'>
<Icon name='puzzle piece' color='teal' />
Register to DevChat
</Header>
<Form size='large' onSubmit={onFormSubmit}>
<Segment stacked>
<Form.Input
fluid
type='text'
icon='user'
iconPosition='left'
placeholder='Username'
onChange={onUsernameChange}
value={username}
/>
<Form.Input
fluid
type='email'
icon='mail'
iconPosition='left'
placeholder='Email'
onChange={onEmailChange}
value={email}
/>
<Form.Input
fluid
type='password'
icon='lock'
iconPosition='left'
placeholder='Password'
onChange={onPasswordChange}
value={password}
/>
<Form.Input
fluid
type='password'
icon='lock'
iconPosition='left'
placeholder='Password Confirmation'
onChange={onPasswordConfirmationChange}
value={passwordConfirmation}
/>
<Button
color='teal'
fluid
size='large'
content='Submit'
/>
</Segment>
</Form>
{
registerErrors.length > 0 &&
<Message error>
<h3>Please note</h3>
{showErrors()}
</Message>
}
<Message>
Already a user? <Link to='/login'>Login</Link>
</Message>
</Grid.Column>
</Grid>
)
}
export default Register;
答案 0 :(得分:1)
这是常见的useState
陷阱。
setRegisterErrors([])
有效,因为它被调用,所以没有机会不起作用。它触发同步组件更新。由于onFormSubmit
之后没有退出,因此之后会调用setRegisterErrors(registerErrors.concat(error))
,其中registerErrors
是在onFormSubmit
之外定义的先前状态。
onFormSubmit
导致2个寄存器状态更新,其中第二个更新(串联的原始数组)将覆盖第一个更新(空数组)。
解决此问题的方法与setState
相同,使用状态更新程序功能提供要更新的当前状态:
setRegisterErrors(registerErrors => [...registerErrors, error]);
或者,可以合并寄存器状态更新:
e.preventDefault();
const registerErrors = [];
setUsername('JDoe');
if( isRegisterFormEmpty(username, email, password, passwordConfirmation) ) {
registerErrors.push({message: 'Please fill in all fields'});
} else {
...
}
setRegisterErrors(registerErrors);