如何在使用此关键字的方法中设置类变量的状态

如何解决如何在使用此关键字的方法中设置类变量的状态

我正在尝试在Ionic react应用中显示重置服务的结果。我无法使用this.setState({resetSuccess}),因为我正在尝试在方法中执行此操作,而this将引用该方法的范围。 (我还以评论的形式提到了这个问题)

请参考以下代码

private async handleSubmit(e: React.FormEvent,): Promise<any> {
        e.preventDefault();
        try {
            console.log(`These are the reset params---->${JSON.stringify(Reset.resetParams)}`)
            const resetService = new ResetService();
            const resetResponse: ResetResponse = await resetService.reset(Reset.resetParams);
            console.log(`This is the response from the API ----> ${JSON.stringify(resetResponse)}`)

            if (resetResponse.status === 401) {
                console.log("Authentication Failed");

            }
            else if (resetResponse.status === 200) {
                console.log("Password reset successfully");
                const resetSuccess: boolean = true;
                this.setState({ resetSuccess }) // ****How do I set this state? which is in the class's scope?
                Reset.history.push('/login');
            }
        } catch (e) {
            console.log(`Request Failed: ${e}`);
            const resetSuccess: boolean = false;
            this.setState({ resetSuccess })
        }
    }

这是我的渲染功能

    public render() {
        const { resetSuccess,errors } = this.state;
        const context: FormContext = {
            ...this.state,setValues: this.setValues,validate: this.validate
        };
        return (
            <IonPage id="login-registration-page">
                <IonHeader>
                    <IonToolbar color="primary">
                        <IonTitle>Reset Password</IonTitle>
                    </IonToolbar>
                </IonHeader>
                <IonContent>
                    <FormContext.Provider value={context}>
                        <form onSubmit={this.handleSubmit} className="login-registration-form ion-padding">
                            <div className="container">
                                {this.props.render()}
                                <div className="form-group">
                                    <IonButton
                                        type="submit"
                                        disabled={!this.completeValidation}
                                        expand="block"
                                    >Submit</IonButton>
                                </div>
                                {resetSuccess === true && (     //*****This is what I am trying to display based on the outcome
                                    <div className="alert alert-info" role="alert">
                                        Password reset successfull. You will be redirected shortly to the login page
                                    </div>
                                )}
                                {resetSuccess === false &&
                                    (
                                        <div className="alert alert-danger" role="alert">
                                            Either the link that you have clicked on or the current password you provided is incorect. Please use the right verification link you received and input the correct password.
                                        </div>
                                    )}
                            </div>
                        </form>
                    </FormContext.Provider>
                </IonContent>
            </IonPage>
        )
    }

解决方法

有两种方法可以执行此操作,但是我建议使用一个函数,该函数使用正确的handleSubmit处理函数返回所需的setState函数。通过使用返回函数的函数,您可以访问组件的范围,以将所需的setState方法传递给handleSubmit函数。

private async handleSubmit(): 
  (e: React.FormEvent) => Promise<any> {
        const setState = this.setState; // Define local reference to setState

        return (e: React.FormEvent) => {
        e.preventDefault();
        try {
            console.log(`These are the reset params---->${JSON.stringify(Reset.resetParams)}`)
            const resetService = new ResetService();
            const resetResponse: ResetResponse = await resetService.reset(Reset.resetParams);
            console.log(`This is the response from the API ----> ${JSON.stringify(resetResponse)}`)

            if (resetResponse.status === 401) {
                console.log("Authentication failed");

            }
            else if (resetResponse.status === 200) {
                console.log("Password reset successfully");
                const resetSuccess: boolean = true;
                setState({ resetSuccess }) // Now referring to your local reference
                Reset.history.push('/login');
            }
        } catch (e) {
            console.log(`Request failed: ${e}`);
            const resetSuccess: boolean = false;
            setState({ resetSuccess }) // Now referring to your local reference
        }
      }
  }

然后在您的render方法中,调用handleSubmit方法,因为它现在返回了所需的处理程序:

<form onSubmit={this.handleSubmit()} className="login-registration-form ion-padding">
,

将handleSubmit方法绑定到构造函数中的类起作用。

  constructor(props: any) {
        super(props);
        const errors: Errors = {};
        const values: Values = {};
        this.state = {
            errors,values
        };
        this.currentPasswordProvided = false;
        this.passwordValidated = false;
        this.completeValidation = false;
        this.emailAddress = '';
        Reset.history = this.props.history;
        this.handleSubmit=this.handleSubmit.bind(this) //<------ Binding it to the class is required because when the submit is clicked,the handler gets unmounted,and this will not be defined in the handleSubmit.
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?