我有一个相当基本的登录设置(下面的代码),其中包含一些需要身份验证的组件。当我导航到http://localhost:8000/时,它会重定向到http://localhost:8000/login并且一切都很好。如果我随后登录,它会返回http://localhost:8000/并显示我的主要组件。
但是,当我直接导航到http://localhost:8000/login时,它会显示“无法获取 /login”。我的“关于”组件也是如此。当我添加一个磅符号时它确实有效:http://localhost:8000/#/login。谁能解释发生了什么?
var React = require('react');
var Main = require('./components/main');
var Login = require('./components/login');
var About = require('./components/about');
var SessionStore = require('./stores/session-store')
import createBrowserHistory from 'history/lib/createBrowserHistory';
import { Router, Route, Link, History, IndexRoute } from 'react-router';
var App = React.createClass({
render: function() {
return <div>
{this.props.children}
</div>
}
});
function requireAuth(nextState, replaceState) {
if(!SessionStore.isLoggedIn()){
replaceState({ nextPathname: nextState.location.pathname }, '/login');
}
}
function redirectIfLoggedIn(nextState, replaceState){
if(SessionStore.isLoggedIn()){
replaceState({ nextPathname: nextState.location.pathname }, '/');
}
}
var routes = (
<Router history={createBrowserHistory()}>
<Route path="/" component={App}>
<IndexRoute component={Main} onEnter={requireAuth}/>
<Route path="login" component={Login} onEnter={redirectIfLoggedIn} />
<Route path="about" component={About} onEnter={requireAuth} />
</Route>
</Router>
)
React.render(routes, document.querySelector('.container'));