【问题标题】:React - history.push redirect not workingReact - history.push 重定向不起作用
【发布时间】:2021-01-04 02:05:52
【问题描述】:

我正在尝试使用.then 类型的ajax 在登录后重定向我的页面。除了history.push() 命令,一切正常:

axios
  .post('http://localhost:8080/login', {
    email,
    password
  })
  .then((res) => {
    sessionStorage.token = res.data.token;
    const { sub } = JSON.parse(atob(res.data.token.split('.')[1]));
    sessionStorage.email = sub;
  })
  .then(() => history.push("/reservations"))
  .catch(() => setError(connectionError))
}

它不是重定向,而是正确登录但不更改页面。刷新时页面会更新,但仍然没有重定向。 不确定这是否重要,但这是我的路线:

<Route path="/reservations" exact component={Reservations}/>

帮助非常感谢

【问题讨论】:

  • 可能还有其他问题,但.then(history.push("/reservations")) 是错误的。应该是.then(() =&gt; history.push("/reservations"))
  • 嗨,我也面临同样的问题。您找到解决方案了吗?

标签: javascript reactjs ajax redirect browser-history


【解决方案1】:

最后一个.then 的语法有问题。不应该是一个回调方法,在里面你会调用history.push吗?

类似这样的:

axios
  .post('http://localhost:8080/login', {
    email,
    password
  })
  .then((res) => {
    sessionStorage.token = res.data.token;
    const { sub } = JSON.parse(atob(res.data.token.split('.')[1]));
    sessionStorage.email = sub;
  })
  .then(() => history.push("/reservations"))
  .catch(() => setError(connectionError))
}

【讨论】:

【解决方案2】:

我会添加来自 SiddAjmera 的答案,如果历史仍然不起作用,你必须添加一个包历史

npm 安装历史记录

index.js

import React from "react";
import ReactDOM from "react-dom";
import { Router } from "react-router";
import { createBrowserHistory } from "history";

export const history = createBrowserHistory();

ReactDOM.render(
  <Router history={history}>
    <App />
  </Router>,
  node
);
import {history} from "./index"
axios
  .post('http://localhost:8080/login', {
    email,
    password
  })
  .then((res) => {
    sessionStorage.token = res.data.token;
    const { sub } = JSON.parse(atob(res.data.token.split('.')[1]));
    sessionStorage.email = sub;
  })
  .then(() => history.push("/reservations"))
  .catch(() => setError(connectionError))
}

【讨论】:

  • 我会试试这个,但我使用的是来自react-router-domuseHistory
【解决方案3】:

试试这个方法:

axios
      .post('http://localhost:8080/login', {
        email,
        password
      })
      .then((res) => {
        sessionStorage.token = res.data.token;
        const { sub } = JSON.parse(atob(res.data.token.split('.')[1]));
        sessionStorage.email = sub;
        history.push("/reservations");
      })
      .catch(() => setError(connectionError))
    }

【讨论】:

    【解决方案4】:

    .then(history.push("/reservations")) 更改为.then(() =&gt; history.push("/reservations"))

    【讨论】:

      猜你喜欢
      • 2018-07-15
      • 1970-01-01
      • 2021-02-20
      • 2019-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 2017-10-05
      相关资源
      最近更新 更多