这里真的很困惑。我更新到了 React Router 4,这需要一些更改,现在当我的注册表单在服务器端出现错误时,它会返回控制台错误: 这是回调。
setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the RegisterForm component.
真正令人困惑的是,如果我在我不知道的 Accounts.createUser
函数之外运行 this.setState({ error: {createUserError: "Test error"}});
没有收到控制台错误。
有什么建议吗???
handleSubmit(event) {
event.preventDefault();
this.setState({errors: {} }, function() {
var data = {
email: this.state.email,
password: this.state.password
};
Accounts.createUser(data, (error) => { // This arrow function preserves this
if(error) {
this.setState({ errors: {createUserError: error.reason }});
}
});
});
}
最佳答案
当 Accounts.createUser
生成的 HTTP 请求返回错误时,handleSubmit
绑定(bind)到的组件已被卸载,这就是调用 setState 的原因
生成错误。
一种选择是将 handleSubmit
移动到在表单提交时不会卸载的父级,并将该函数作为 prop 向下传递。另一种选择是使用 redux 或 Flux 进行状态管理。
另一个选项是保持组件的安装状态,直到 Accounts.createUser
成功返回,这将允许您在出现错误时在表单上显示消息。例如,您可以指示哪些字段无效。
关于reactjs - 如何停止卸载组件的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44172258/