簡體   English   中英

React - history.push 重定向不起作用

[英]React - history.push redirect not working

我正在嘗試使用.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嗎?

像這樣的東西:

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

我將添加來自 SiddAjmera 的答案,如果歷史仍然不起作用,則必須添加 package 歷史

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

試試這種方式:

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

.then(history.push("/reservations"))更改為.then(() => history.push("/reservations"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM