简体   繁体   English

如何在反应中的 axios 响应之后有条件地重定向到页面?

[英]How can I conditionally redirect to a page after the axios response in react?

How can I conditionally redirect to a page if the axios api is empty or a state is empty initially.如果 axios api 为空或状态最初为空,我如何有条件地重定向到页面。 In the following code I'm updating the state using axios and the user information is available in the state but the code keeps on calling to the http://userapi.com/login in loop.在下面的代码中,我使用 axios 更新状态,并且用户信息在状态中可用,但代码继续调用http://userapi.com/login循环。 What I'm trying to achieve is, if the userinfo state is empty initially then redirect to the login page and authenticate.我想要实现的是,如果 userinfo 状态最初为空,则重定向到登录页面并进行身份验证。

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>
    )
  }
}

I'm able to redirect fine but issue is with continuous loop.我能够很好地重定向,但问题在于连续循环。 Even though the user information is storing the redirection is called (happens in loop)即使用户信息正在存储重定向被调用(发生在循环中)

Axios returns Promise so the code with if condition below executes before the function that updates the state in then block. Axios 返回Promise,因此下面的if条件代码在更新then块中状态的函数之前执行。 So if you need to check the updated state value after the request is successful, put your conditional inside then block.因此,如果您需要在请求成功后检查更新的状态值,请将您的条件放入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);
      });
  }

You can try the following approach:您可以尝试以下方法:

class HeaderComponent 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)
    })
  }
  componentDidUpdate(prevProps, { userinfo }) {
    if (userinfo !== this.state.userinfo
        && Object.keys(this.state.userinfo.w3idUser || {}).length === 0) {
        window.location = 'http://userapi.com/login';
    }
  }
  render() {
    return (
      <React.Fragment>
        <Header>Welcome</Header>
      </React.Fragment>
    )
  }
}

The problem was that this.state.w3idUser never exists since you're mapping the response into userInfo state.问题是this.state.w3idUser永远不存在,因为您将响应映射到userInfo状态。

i guess the issue is componentDidMount , you are redirecting before axios finish it's get request, refactor your code like below, you can show the sort of spinner until axios return value:我猜问题是componentDidMount ,你在 axios 完成它的get请求之前重定向,像下面这样重构你的代码,你可以显示微调器的种类,直到 axios 返回值:

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

} }

it depends on the router you're using but if you want the javascript way check the code below:这取决于您使用的路由器,但如果您想要 javascript 方式,请检查以下代码:

// Simulate a mouse click:
window.location.href = "http://www.w3schools.com";

// Simulate an HTTP redirect:
window.location.replace("http://www.w3schools.com");

Here when you are getting response...在这里,当您收到回复时...

.then(res => {
        const userinfo = res.data;
        this.setState({ userinfo });
    })

Check the res.data for user info.检查 res.data 以获取用户信息。 If you did receive a user then you can setState, if no user redirect to login page.如果您确实收到了用户,那么您可以设置状态,如果没有用户重定向到登录页面。

As far as redirecting look into react-router or react-router-dom至于重定向查看react-routerreact-router-dom

I wouldn't use pure javascript for redirecting/navigating in a React App.我不会使用纯 javascript 在 React 应用程序中重定向/导航。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM