我有一个非常简单的表单,我将用户电子邮件存储在组件的状态中,并使用 onChange 函数更新状态。发生了一件奇怪的事情,如果我的 onChange 函数使用函数更新状态,那么每当我输入时,我都会在控制台中收到两个错误。但是,如果我用对象更新状态,则不会出现任何错误。我相信使用函数更新是推荐的方法,所以我很想知道为什么会出现这些错误。
我的组件:
import * as React from 'react';
import { FormGroup, Input, Label } from 'reactstrap';
interface IState {
email: string;
}
class SignUpForm extends React.Component<{}, IState> {
constructor(props: {}) {
super(props);
this.state = {
email: ''
};
}
public onEmailChange = (event: React.ChangeEvent<HTMLInputElement>) => {
this.setState(() => ({ email: event.currentTarget.value }))
};
// Using this function instead of the one above causes no errors
// public onEmailChange = (event: React.ChangeEvent<HTMLInputElement>) => {
// this.setState({ email: event.currentTarget.value })
// };
public render() {
return (
<div>
<h1>Sign Up</h1>
<div className='row' style={{ paddingTop: '20px' }}>
<div className='col-lg-4 offset-lg-4'>
<form>
<FormGroup style={{ textAlign: 'left' }}>
<Label>Email</Label>
<Input
value={this.state.email}
onChange={this.onEmailChange}
type='text'
placeholder='Email Address'
/>
</FormGroup>
</form>
</div>
</div>
</div>
);
}
}
export default SignUpForm;
我得到的错误信息是:
index.js:2178 Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the method `currentTarget` on a released/nullified synthetic event. This is a no-op function. If you must keep the original synthetic event around, use event.persist(). See react-event-pooling for more information.
index.js:2178 Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: react-controlled-components
最佳答案
如果您的状态更新是从您当前的状态中派生的(例如,递增 count
变量),您应该使用 setState
的更新函数版本。
如果您只是像使用事件处理程序一样设置一个全新的值,则不需要使用更新函数版本。您问题中的注释版本非常好。
如果您想使用更新功能版本,您必须使用 event.persist()
这样您就可以异步使用事件,或者在调用 setState
之前简单地提取值。
public onEmailChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { value } = event.currentTarget;
this.setState(() => ({ email: value }))
};
关于javascript - 使用箭头函数 react this.setState 导致控制台出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51686778/