[英]React.js - can't update form that is based on state
我正在尝试做一个基本的事情:插入数据,该数据将传递回主组件,并显示项目列表,可以在表单中单击和编辑这些项目。
这是代码的相关部分:
class SimpleForm extends React.Component {
constructor() {
super();
this.state = {
id: null,
firstName: ''
};
}
static getDerivedStateFromProps(props, state) {
if (props.user === null) return null;
return {
id: props.user.id,
firstName: props.user.firstName
}
}
handleChange = e => {
const value = e.target.value;
this.setState(prevState => {
return {
firstName: value
}
});
}
handleSubmit = e => {
e.preventDefault();
const event = e.target;
this.props.onAdd(this.state);
this.setState(prevState => {
return {
id: null,
firstName: ''
};
}, () => {
event.reset();
});
}
render() {
const {
firstName
} = this.state;
return ( <form onSubmit = {this.handleSubmit}>
<input type = "text"
name = "firstName"
value = {firstName}
onChange = {this.handleChange} />
<input type = "submit" value = "Submit" />
</form>
);
}
}
这是示例: http : //jsbin.com/yawasoz/1/edit?html,js,output
如果插入一项,然后单击“ LI”元素,则会看到表单中的状态已正确设置。 但是,您根本无法编辑输入中的数据-输入时,文本保持不变。 就像“ onChange”方法不存在一样。 这里发生了什么? 我认为我可能使用了“ getDerivedStateFromProps”错误?
显然,这是最新版本的React中的错误(如https://www.reddit.com/r/reactjs/comments/8mslha/cant_update_form_that_is_based_on_state/dzq4zen所述 ),降级至16.3的工作符合预期: http:// jsbin.com/wilahihuyu/1/edit
<script crossorigin src="https://unpkg.com/react@16.3/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16.3/umd/react-dom.development.js"></script>
编辑
根据github上的讨论,这不是错误,该错误存在于代码中,版本16.4显而易见。 这里是讨论: https : //github.com/facebook/react/issues/12898#issuecomment-392035163
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.