首页 > 解决方案 > React JS make async call without componentdidmount()

问题描述

I'm trying to do an API call triggered only when the user clicks on the submit button

This is in a user login context where the parent's component state gets changed.

import React from 'react';
import {Button, FormGroup, FormControl, ControlLabel} from "react-bootstrap";
import './login.css';

export default class loginForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: '',
      answer:[],
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  async handleSubmit(event) { 
    const jso = JSON.stringify({
      username: this.state.username,
      password: this.state.password
    })
    const response = await fetch("https://app.herokuapp.com/authentication", {
      method: 'POST',
      mode: 'cors',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: jso,
    })

    const json = await response.json()
       
    this.setState({answer:json});

    //check if user is authentificated
    alert("Server Answer : "+ this.state.answer.answer);
    if(this.state.answer.answer.localeCompare('true') == 0){
      this.props.app.setState({auth: true});
      sessionStorage.setItem('auth', true);
    }
    else if (this.state.username != ""){
      alert("INCORRECT USERNAME PASSWORD ");
    }
  }


  render() {
    
    return (<div className="Login">
      <form onSubmit={this.handleSubmit}>
        //part omitted because not relevant for this question
        <Button bsSize="small" color="primary" type="submit">
          Login
        </Button >
      </form>
    </div>)
  }
}

My question: Is it possible to do something like this or I absolutely need to use componentDidMount() ?

I've been struggling / searching about this for too much time now and I still can't find a way to make it work.

标签: reactjsfetch

解决方案


有可能做到这一点。据我所知,一旦到达//check if user is authentificated. 发生这种情况是因为 reactsetState是异步的。

为了在修改后立即访问状态,该setState函数采用可选的回调函数,因此您可以尝试编写如下代码:

this.setState({answer:json}, () => {
    //check if user is authentificated
    alert("Server Answer : "+ this.state.answer.answer);
    if(this.state.answer.answer.localeCompare('true') == 0){
      this.props.app.setState({auth: true});
      sessionStorage.setItem('auth', true);
    }
    else if (this.state.username != ""){
      alert("INCORRECT USERNAME PASSWORD ");
    }
});

推荐阅读