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

我在很多地方读过我不应该使用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");

    };


侃侃尔雅
浏览 165回答 4
4回答

萧十郎

setState是异步的,所以当你这样做的时候this.props.onLogIn,状态中的值还没有更新。您需要在 setState 的回调中运行最后几行。查看何时使用 React setState 回调

猛跑小猪

使用 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是true:submitForm = () => {    this.setState({        isAuthenticated: true,    });    this.props.onLogIn(true, this.state.userName);    this.props.history.push("/predict");};

弑天下

setState 是异步的,因此当您执行 this.props.onLogIn 时,如果没有一次渲染,状态中的值不会更新。像这样检查 setState 的第二个参数。submitForm = () => {    this.setState({        isAuthenticated: true,        userName: this.state.userName,    }, () => {        this.props.onLogIn(this.state.isAuthenticated, this.state.userName);        this.props.history.push("/predict");    });};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript