【问题标题】:Strange navigation issue with react-routerreact-router 出现奇怪的导航问题
【发布时间】:2015-12-12 23:57:47
【问题描述】:

我有一个相当基本的登录设置(下面的代码),其中包含一些需要身份验证的组件。当我导航到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'));

【问题讨论】:

    标签: reactjs react-router react-router-component


    【解决方案1】:

    快速回答,http://localhost:8000/#/login 正在您浏览器中的 javascript 应用程序中运行,因此该应用程序由 express Web 服务器从/ 提供服务,因此/(app)#/login 和@ 987654326@ 不向服务器请求任何内容,而是 JS 应用程序中的路由 (react-routes) 以呈现各种组件。当您直接输入/login 时,它必须查询快速网络服务器,但您没有设置任何快速服务器路由,除了在根/ 处为应用程序提供服务的路径。

    所以它归结为react-routes,一个相关的问题询问如何删除它,但请注意,截至 15 年 10 月,react-router 从版本 0.13 更改为 1.0,这对 API 进行了相当大的更改,所以在使用时要小心阅读示例以了解版本 How to stop /#/ in browser with react-router?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 2023-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多