首页 文章

React Router(v3)重定向不重定向到新位置

提问于
浏览
2

我有这样的路由器设置:

import React from 'react';
import {IndexRoute, NotFoundRoute, Route, Redirect} from 'react-router';

import App from './components/app';
import Home from './components/Home';
import AuthorPage from './components/authors/AuthorPage';
import About from './components/about/About';
import NotFound from './components/NotFound';

const routes = (
    <Route path="/" component={App} >
      <IndexRoute component={Home} />
      <Route path="about" component={About} />
      <Route path="authors" component={AuthorPage} />
      <Route path="*" component={NotFound} />
      <Redirect from="/about-us" to="/about" />
    </Route>
);

export default routes;

除了重定向之外的一切工作都很好 . 每当我尝试导航到 /about-us 时,我都会看到一个显示 Cannot GET /about-us 的白页 .

似乎无法在文档中找到任何相关内容 . 路由的“起始”部分是否仍然必须存在才能发挥作用,或者它是否只是重定向我?

编辑:

我还应该提一下,我使用历史包,如react-router升级指南中所述: https://github.com/rackt/react-router/blob/master/upgrade-guides/v1.0.0.md

这是我的main.js:

import React from 'react';
import ReactDOM from 'react-dom';
import Router from 'react-router';
import routes from './routes';
import createBrowserHistory from 'history/lib/createBrowserHistory'

// Using history to avoid default behavior of weird urls like `?_k=umhx1s`
// See:  https://github.com/rackt/react-router/blob/master/upgrade-guides/v1.0.0.md
let history = createBrowserHistory();
const root = document.getElementById('app');

ReactDOM.render(<Router history={history}>{routes}</Router>, root);

2 回答

  • 1

    好像你在那里打错了 . 在你的路线中,你有 <Route path="about" component={About} /> 注意到你有 path="about" 并且你正试图导航到 /about-us . 这与你的任何路线都不匹配 . 尝试导航到 /about 或将您的路线更改为 <Route path="about-us" component={About} /> .

  • 1

    结果我的路线顺序错了 . 我的“全部捕获”NotFound路由需要在重定向后才能使用 .

    import React from 'react';
    import {IndexRoute, NotFoundRoute, Route, Redirect} from 'react-router';
    
    import App from './components/app';
    import Home from './components/Home';
    import AuthorPage from './components/authors/AuthorPage';
    import About from './components/about/About';
    import NotFound from './components/NotFound';
    
    const routes = (
      <Route path="/" component={App} >
        <IndexRoute component={Home} />
        <Route path="about" component={About} />
        <Route path="authors" component={AuthorPage} />
        <Redirect from="about-us" to="about" /> // Switched order with below Route.
        <Route path="*" component={NotFound} />
      </Route>
    );
    
    export default routes;
    

相关问题