使用react-router时遇到的奇怪导航问题

15 浏览
0 Comments

使用react-router时遇到的奇怪导航问题

我有一个相当基本的登录设置(以下是代码),其中有几个组件需要进行身份验证。当我导航到http://localhost:8000/时,它会重定向到http://localhost:8000/login,一切正常。如果我登录,它会返回到http://localhost:8000/并显示我的主要组件。

然而,当我直接导航到http://localhost:8000/login时,它显示“无法获取/login”。我的“about”组件也是同样的情况。当我添加井号时它才能正常工作: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 (
      {this.props.children}
    );
  }
});
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 = (
  
    
      
      
      
    
  
);
React.render(routes, document.querySelector('.container'));

0
0 Comments

问题的原因是因为React Router的路由配置导致了奇怪的导航问题。当访问http://localhost:8000/#/login时,实际上是在浏览器中运行的JavaScript应用程序,该应用程序由Express Web服务器从/进行提供。因此,/(app)#/login/#/about并不是从服务器请求任何内容,而是JS应用程序(react-routes)中的路由,用于渲染不同的组件。当直接输入/login时,它必须向Express Web服务器发起查询,但是除了用于在根目录/提供应用程序的路由之外,您没有设置任何Express服务器路由。

解决方法是通过修改React Router的配置来解决这个问题。根据相关问题的回答,可以找到如何解决这个问题的方法。需要注意的是,自2015年10月起,React Router从0.13版本更改为1.0版本,API发生了相当大的变化,因此在阅读示例时要小心注意版本。

参考链接:How to stop /#/ in browser with react-router?

0