我正在尝试构建一个单页应用程序,但我遇到了Routes的一些问题。
在下面的代码中,我正在检查我是否已经拥有令牌,如果我没有,我会将用户重定向到使用browserHistory.push的登录页面。
网址更新为“chrome://inspect/#devices”,但页面无法刷新。
//Home.js
import React from "react";
import docCookies from "docCookies";
import { Router, browserHistory } from "react-router";
export default class Home extends React.Component {
componentWillMount() {
console.log("Component mounted");
if (docCookies.getItem("token")) {
console.log("token found"); // If a token is found render should fire
}
else {
console.log("Tryng to transition");
browserHistory.push("/login"); //Trying to redirect to the login page
}
}
render() {
return (<h1>This is home</h1>);
}
}
编辑:这是我的路线定义的文件
import React from "react";
import {Route, Router, hashHistory, IndexRoute} from "react-router";
import Home from "./home/Home";
import Login from "./login/Login";
export default class Layout extends React.Component {
constructor() {
super();
this.state = {token: ""};
}
render() {
return (
<div>
<Router history={hashHistory}>
<Route path="/" component={Home}/>
<Route path="login" component={Login} />
</Router>
</div>
)};
}
提前致谢。