【发布时间】:2017-11-07 19:51:54
【问题描述】:
我是 React 新手,目前正在研究导航栏。我有 index.js 这是我的启动文件
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import history from 'history';
import Routes from './routes/index';
import Template from './containers/Template';
ReactDOM.render(
(
<BrowserRouter
history={history}
routes={Routes}
>
<Template />
</BrowserRouter>
),document.getElementById('root')
);
路由是从如下所示的 routes/index.js 文件中导入的
import React from 'react';
import {Route, BrowserRouter, Switch} from 'react-router-dom';
import Template from '../containers/Template';
import Home from '../containers/Home';
import Profile from '../containers/Profile';
const createRoutes = () => {
return (
<BrowserRouter>
<Switch>
<Route path= '/' component= {Template}/>
<Route path= '/' component={Home}/>
<Route path= {'/profile'} component={Profile}/>
</Switch>
</BrowserRouter>
)
}
const Routes = createRoutes();
export default Routes;
我的主要问题是,当我使用 chrome 和 React Developer 工具时,我可以看到与 BrowserRouter 对象相关的路由,如下所示 Routes in the Browser element inspection
但是我无法打开任何指定的路由总是得到“无法获取 /profile”,请注意我使用 webpack 作为 web 开发包。
【问题讨论】:
-
一个导航栏应该有链接标签的权利,你为什么要为你的导航栏放置一个路由器。路由文件将是不同的,并且独立于任何组件。
-
我认为这与您将
<BrowserRouter />传递给自身有关。那我相信你需要指定历史对象import createHistory from 'history/createBrowserHistory'。此外,查看 API<BrowserRouter />不接受history属性。 reacttraining.com/react-router/web/api/BrowserRouter -
谢谢你们两位我刚读了这篇文章是否说明了@VivekN 所说的medium.freecodecamp.com/… 我可以使用react 对象在没有路由器的情况下操作页面
-
@rockchalkwushock 是的,只是注意到了这一点,但它在添加它时从未说明任何错误,所以我基本上应该创建一个导入历史并扩展它的类..
标签: javascript reactjs react-router react-router-dom