如何解决反应 - history.push 重定向不起作用
我试图在登录后使用 .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 的答案,如果历史仍然不起作用,您必须添加一个包历史
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',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"))
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。