![](/img/trans.png)
[英]How do I pass a function using “this” keyword into a JavaScript Class?
[英]How do I set the status of a variable of a class in a method that using this keyword
我正在嘗試在我的 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> ) }
有幾種方法可以做到這一點,但我建議使用一個函數,該函數使用正確的setState
處理程序返回所需的handleSubmit
函數。 通過使用返回函數的函數,您可以訪問組件的范圍,將所需的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
}
}
}
然后在您的渲染方法中,改為調用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. }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.