首页 > 解决方案 > 在 axios 响应做出反应后,如何有条件地重定向到页面?

问题描述

如果 axios api 为空或状态最初为空,我如何有条件地重定向到页面。在下面的代码中,我使用 axios 更新状态,并且用户信息在状态中可用,但代码继续调用http://userapi.com/loginin 循环。我想要实现的是,如果用户信息状态最初为空,则重定向到登录页面并进行身份验证。

class MyComponent extends React.Component {
  constructor() {
    super()
    this.state = {
      userinfo:{}
    }
  }
  
  componentDidMount(){
    axios.get('http://userapi.com/user')
    .then(res => {
        const userinfo = res.data;
        this.setState({ userinfo });
    })
    .catch(err => {
        console.log("Fetch error", err)
    })
    if (Object.keys(this.state.userinfo).length === 0) {
        window.location = 'http://userapi.com/login';
    }
  }
  render() {
    return (
      <React.Fragment>
        <Header>Welcome</Header>
      </React.Fragment>
    )
  }
}

我能够很好地重定向,但问题在于连续循环。即使用户信息正在存储重定向被调用(发生在循环中)

标签: javascriptreactjs

解决方案


Axios 返回Promise,因此具有if以下条件的代码在更新块中状态的函数之前执行then。因此,如果您需要在请求成功后检查更新的状态值,请将您的条件放在then块内。

componentDidMount() {
    axios
      .get('http://userapi.com/user')
      .then((res) => {
        const userinfo = res.data;
        this.setState({ userinfo }, () => {
          if (Object.keys(this.state.userinfo).length === 0) {
            window.location = 'http://userapi.com/login';
          }
        });
      })
      .catch((err) => {
        console.log('Fetch error', err);
      });
  }

推荐阅读