使用Axios和React进行重定向

6

我遇到了Axios方面的问题,不知道在注册或登录后如何进行重定向。

以下是我的代码:

axios.post("/api/user/signup", { data })
  .then(res => {
    if (res.status === 200) {
      console.log("REDIRECTION avec status => ", res.status);
      // how to redirect here
      <Redirect to = {{ pathname: "/home" }} />
    }

代码执行到console.log语句,但我不知道如何在React中进行重定向。

1个回答

12

根据您使用Redirect组件的方式,我假设您正在使用React Router作为路由逻辑库。

React Router(v4)处理呈现时的路由。

这意味着重定向将在渲染Redirect组件时发生。

控制此行为的一种方法是利用状态。

在React中,更改状态会导致重新渲染。

以下是一种方法:

class MyComponent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      isSignedUp: false // <-- initialize the signup state as false
    }
  }

  signup() {
    return axios.post("/api/user/signup", { data })
      .then(res => {
        if (res.status === 200) {
          this.setState({ isSignedUp: true }); // after signing up, set the state to true. This will trigger a re-render
        }
  }

  // ...

  render() {
    if (this.state.isSignedUp) {
      // redirect to home if signed up
      return <Redirect to = {{ pathname: "/home" }} />;
    }

    // ... rest of rendering code    
  }

你好,是的,当然可以,完美的,我会尝试。 - Jim
axios.post必须在函数中吗?还是可以像您所做的那样在组件中使用? - Jim
在一个函数中,你现在把它放在哪里了?就把它放在原来的位置。 - nem035
我在我的函数postData中,该函数通过表单的onChange调用。 - Jim
当然,没有必要改变那个。 - nem035
@jim2k 很高兴能帮助你,伙计 :) - nem035

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接