我有我一直在使用ES6类创建的形式。该表格是有状态的,并更新其状态onChange。表单状态中的信息通过onSubmit传递给应用程序组件。我可以通过在表单和应用程序组件的方法中传递的状态来控制console.log的每一个步骤,并且其行为与预期相同。在这个代码示例中,我在应用程序中设置了setState后拥有了控制台,并按照我的预期注销了添加了输入值的状态对象。作出反应状态的应用程序没有更新,但我可以CONSOLE.LOG正确更新的状态
问题是,当我看在反应开发工具,国家并没有更新。另外,如果我将控制台语句移到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>
);
}
}
谢谢!您的建议与使用redux工具逐步完成状态有关吗?我还没有尝试过,但我觉得我已经阅读过有关这种情况的文章。 。 – CaptainJ
这是对反应成分,在终极版也在里面,你应该永远不会发生变异的状态值,这个语句查询,**“减速是‘纯函数’他们应该不会有任何副作用,也没有发生变异的状态 - 他们必须返回修改后的副本“**检查这篇文章:https://medium.com/@stowball/a-dummys-guide-to-redux-and-thunk-in-react-d8904a7005d3 –