登录功能中获取API时如何显示加载进度?

问题描述 投票:0回答:2

当我尝试获取用于登录的 API 时,我陷入了某些显示 loading 的项目。我用

考虑下面的代码:

login(){
  const { history } = this.props;
    PostData('api/users/login', this.state)
    .then ((result) => {
      let responseJSON = result;
      this.setState({
        loaded: true
      })
      if(this.state.loaded === true){
      if(responseJSON.success === true){
        localStorage.setItem('loginEmail', this.state.loginEmail);
        localStorage.setItem('id', responseJSON.user.id);

        history.push('/Home')    // when successfully login, it will go to Home Page

      }else if(responseJSON.success === false){
        alert("Wrong User Credential")
      }}else if(this.state.loaded === false){
        return(
         <LinearProgress />    // for loading
        )
      }
    }).catch((error) => {
      console.log(error)
    })
}

这是我的 this.state 构造函数

constructor (props){
  super(props);
  this.state ={
    loginEmail: '',
    loginPassword: '',
    error: {},
    loaded: false,
    history: PropTypes.object.isRequired
  }
  this.login = this.login.bind(this);
  this.onChange = this.onChange.bind(this);
}

我在登录功能中使用的加载方式是否错误?为什么加载错误时无法显示线性进度

更新 这是我来自codesandbox的代码

javascript reactjs loading
2个回答
0
投票

从登录功能中删除 else if 大小写。这个。

else if (this.state.loaded === false) {
      return (
        <LinearProgress /> // for loading
      );
    }

并在登录输入字段下方的渲染中添加一个三元条件来检查状态,如果状态为 false 则渲染

<LinearProgress />
,并且当登录使状态为 true 时,将移至下一页。

        <input
          type="submit"
          value="Login"
          className="logbtn"
          onClick={this.login}
        />
{(this.state.loaded)?null: <LinearProgress />}

0
投票

根据您的沙箱,您需要添加/更改一些内容

  • loaded
    重命名为
    isLoading
    参数到您的
    state
    ,这样会更容易理解它的可用性
this.state = {
    loginEmail: "",
    loginPassword: "",
    error: {},
    redirect: false,
    isLoading: false,
    history: PropTypes.object.isRequired
};
  • 触发呼叫时触发状态更改为
    true
    ,有多种方法可以做到这一点,但最简单的是直接在
    isLoading
    函数中更改
    login
  • 添加一个
    finally
    承诺处理程序,以便在调用后将加载状态更改为 false,无论成功还是失败。
login() {
  const { history } = this.props;
  this.setState({isLoading:true});
  PostData("api/users/login", this.state)
    .then(result => {
      let responseJSON = result;
        if (responseJSON.success === true) {
          localStorage.setItem("loginEmail", this.state.loginEmail);
          localStorage.setItem("id", responseJSON.user.id);

          history.push("/Home"); // when successfully login, it will go to Home Page
        } else if (responseJSON.success === false) {
          alert("Wrong User Credential");
        }
    })
    .catch(error => {
      console.log(error);
    })
    .finally(() => this.setState({ isLoading : false }));
}
  • 最后一件事是在页面中添加
    <LinearProgress />
    元素并为其设置条件。在你的情况下,
    isLoading
    true
    。您可以通过添加以下行将元素放置在渲染内的任何位置
{this.state.isLoading && <LinearProgress />}
© www.soinside.com 2019 - 2024. All rights reserved.