首页 > 解决方案 > axios调用成功响应后如何重定向

问题描述

我正在拨打 axios 电话,在成功请求后我想请求另一个网页。所以我喜欢

getShow = event =>{
    event.preventDefault();
    const headers = {
     'Content-type': 'application/json',
      Authorization: 'Client ' + localStorage.getItem('secretKey')
    };
    axios
      .get('/api/getshow', {
        headers: headers,
        params: {
          name: this.state.sendername,
          email:this.state.senderemail
        }
      })
      .then(res => {
        console.log(res.data.name);
        return <Redirect to='/show?name=res.data.name'/>

      });
  };

但这不是重定向。我也尝试删除 event.preventDefault(); 但没有用。感谢任何帮助。

标签: reactjsreact-routeraxios

解决方案


创建一个称为重定向的状态:

constructor(props) {
    super(props);
    this.state = { redirect: null }
}

或者用钩子:

const [ redirect, setRedirect ] = useState(null);

您需要在渲染中设置组件:

if (redirect) {
    return <Redirect to={redirect} />
}

然后在你的 axios 的那个 .then 中,只需将重定向设置为你想要重定向的路由:

axios
  .get('/api/getshow', {
    headers: headers,
    params: {
      name: this.state.sendername,
      email:this.state.senderemail
    }
  })
  .then(res => {
    console.log(res.data.name);
    //Hooks
    setRedirect(`/show?${res.data.name}`)
    // No hooks
    this.setState({ redirect: `/show?${res.data.name}` });

  });

推荐阅读