我有一个使用ES6类创建的表格。该表格是有状态的,并更新了其状态。表单状态中的信息传递到App组件OnSubmit。我可以安置在我的表单和应用程序组件的方法中传递的每一步。在此代码示例中,我在应用程序中设置后具有控制台,并且它会随着我的期望添加的输入值登录状态对象。
问题是当我查看React开发人员工具时,该州尚未更新。另外,如果我将控制台语句移至SetState方法中的回调函数,则不会记录任何内容。
我的问题是如何解决此问题,更重要的是,当应用程序中的状态似乎实际上没有实际更新时,我还能使用我要寻找的值登录状态?
class App extends Component {
constructor (props) {
super(props)
this.state = {
appointments: [{title:'first appointment'}]
};
this.updateAppointments = this.updateAppointments.bind(this);
}
updateAppointments(newAppointment) {
var newAppointmentList = this.state.appointments;
newAppointmentList.push(newAppointment);
this.setState= {
appointments: newAppointmentList,
//This console logs nothing
function() {
console.log(this.state.appointments);
}
};
//This console logs out the state as expected with the new appointment
//added even thought the state in the app does not appear to have the
//appointment added when I look in the react dev tools
console.log(this.state.appointments);
}
render() {
return (
<div className="App">
<AppointmentForm addAppointment = {this.updateAppointments} />
</div>
);
}
}
class AppointmentForm extends Component {
constructor (props) {
super(props)
this.state = {
appointmentTitle: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleTitleChange = this.handleTitleChange.bind(this);
}
handleTitleChange(event) {
this.setState({appointmentTitle: event.target.value});
}
handleSubmit(e) {
let newAppointment = {
title: this.state.appointmentTitle
}
e.preventDefault();
this.props.addAppointment(newAppointment);
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<FormGroup controlId="appointmentTitle">
<ControlLabel>Appointment Title</ControlLabel>
<FormControl type="text" placeholder="Appointment Title" value={this.state.appointmentTitle}
onChange={this.handleTitleChange}/>
</FormGroup>
</form>
</div>
);
}
}
您以错误的方式更新状态。
而不是:
this.setState = {
这样写:
updateAppointments(newAppointment) {
var newAppointmentList = this.state.appointments.slice();
newAppointmentList.push(newAppointment);
this.setState({
appointments: newAppointmentList, () => {
console.log(this.state.appointments);
}
})
}
建议:永远不要直接突变状态值,因此首先使用slice()
创建state
数组的副本,然后按新值,然后使用setState
更新state
。
您有一个代码错误。您正在设置setState
属性,而不是调用SetState函数。更改此:
this.setState= {
appointments: newAppointmentList,
function() {
console.log(this.state.appointments);
}
};
:
this.setState({
appointments: newAppointmentList,
function() {
console.log(this.state.appointments);
}
});