为什么 this.state = 错误,如果 this.setState 不起作用?



我在很多地方读到我不应该使用 this.state,而是 this.setState;问题是它不适用于我的代码。我做错了什么?

我正在做的事情有效

submitForm = () => {
this.state.isAuthenticated = true
this.setState({
isAuthenticated: true,
userName: this.state.userName,
});
this.props.onLogIn(this.state.isAuthenticated, this.state.userName);
this.props.history.push("/predict");
};

由于某种原因不起作用的内容

submitForm = () => {
this.setState({
isAuthenticated: true,
userName: this.state.userName,
});
this.props.onLogIn(this.state.isAuthenticated, this.state.userName);
this.props.history.push("/predict");
};

setState是异步的,因此当您执行this.props.onLogIn时,状态中的值尚未更新。您需要在 setState 的回调中运行最后几行。查看何时使用 React setState 回调

setState 是异步的,所以当你这样做时.props.onLogIn,状态中的值没有更新,如果没有一个渲染 .check 在你的第二个 setState 参数中,就像这样。

submitForm = () => {
this.setState({
isAuthenticated: true,
userName: this.state.userName,
}, () => {
this.props.onLogIn(this.state.isAuthenticated, this.state.userName);
this.props.history.push("/predict");
});
};

使用 setState 回调


submitForm = () => {
this.setState((state) => ({
isAuthenticated: true,
userName: state.userName,
}), () => {
this.props.onLogIn(this.state.isAuthenticated, this.state.userName);
this.props.history.push("/predict");
});
};

其他答案解释了 this.setState 是如何异步的。为了解决你关于为什么this.state不起作用的问题:this.state只访问状态的值。不能像设置另一个变量那样设置状态。你需要使用 this.setState。

另一种解决方案是简化您的代码,因为已知 isAuthenticated真的

submitForm = () => {
this.setState({
isAuthenticated: true,
});
this.props.onLogIn(true, this.state.userName);
this.props.history.push("/predict");
};

最新更新