我有一个使用es6类创建的表单。该表单是有状态的并更新其状态onChange。表单状态中的信息将传递给onSubmit上的app组件。我可以通过在表单和应用程序组件的方法中传递状态的每一步调试console.log,它的行为符合预期。在这个代码示例中,我在应用程序中设置了setState之后的控制台,它会根据我的预期添加输入值,从而注销状态对象。
问题是当我查看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>
);
}
}
答案 0 :(得分:3)
您正在以错误的方式更新状态。
而不是:
this.setState = {
像这样写:
updateAppointments(newAppointment) {
var newAppointmentList = this.state.appointments.slice();
newAppointmentList.push(newAppointment);
this.setState({
appointments: newAppointmentList, () => {
console.log(this.state.appointments);
}
})
}
建议:永远不要直接改变状态值,因此首先使用state
创建slice()
数组的副本,然后推送新值,然后使用setState
更新state
。
答案 1 :(得分:2)
您遇到代码错误。您正在设置setState
属性,而不是调用setState函数。改变这个:
this.setState= {
appointments: newAppointmentList,
function() {
console.log(this.state.appointments);
}
};
到此:
this.setState({
appointments: newAppointmentList,
function() {
console.log(this.state.appointments);
}
});
答案 2 :(得分:-1)
在处理任何新状态之前,不要忘记将数组从状态切片。