这是用于遍历routes文件的代码。在这里,我正在创建routerconfig数组,从这里导出到app.js。
import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import routes from './routes';
class RouterConfig extends Component {
render() {
return (
routes.map((route) => {
return (
<Route
key={ route.id }
path={ route.path }
exact={ route.exact }
component={ route.component }
/>
);
})
);
}
}
export default RouterConfig;
这是我的路由配置文件,我在那里列出了所有的路由。
import Home from '../components/home/home';
import About from '../components/about/about';
import Posts from '../components/posts/posts';
import NotFound from '../components/not_found/not_found';
const routes = [
{
path: '/',
exact: true,
component: Home,
id: 'home',
},
{
path: '/about',
component: About,
id: 'about',
},
{
path: '/posts',
component: Posts,
id: 'posts',
},
{
component: NotFound,
id: 'not_found',
},
];
export default routes;
这是我的app.js导入React,{Component}来自'React';从“react-router-dom”导入{Switch,Router,Route};从“。。/Header/Header”导入标头;从“。。/Footer/Footer”导入页脚;从“。。/。。/历史记录”导入历史记录;从“。。/。。/Router/BrowserRoute”导入RouterConfig;
class App extends Component {
render() {
return (
<div>
<Router history={ history } >
<div>
<Header />
<Switch>
<RouterConfig />
</Switch>
<Footer />
</div>
</Router>
</div>
);
}
}
export default App;
问题是在每一页我得到没有发现组件渲染。即使使用带有路由的交换机也不会得到预期的结果。不确定代码不能正常工作的原因。
[这就是它如何呈现不是在每一页中都找到][1]
[1]:https://i.stack.imgur.com/b7evw.png
更改时:
class App extends Component {
render() {
return (
<div>
<Router history={ history } >
<div>
<Header />
<Switch>
<Route exact path='/' component={ Home } />
<Route path='/about' component={ About } />
<Route path='/posts' component={ Posts } />
<Route component={ NotFound } />
</Switch>
<Footer />
</div>
</Router>
</div>
);
}
}
这很好用
您需要将开关
移动到路由配置图
内。React 16 partials的工作方式一定是React路由器中出乎意料的(我真的不确定为什么当交换机在RouterConfig之外时它不工作)。好消息是,至少对我来说,在RouteConfig里面是有意义的。
下面是一个可以工作的codesandbox:
https://codesandbox.io/s/8xmx478kq8
您使用的是哪个版本的React?如果您使用的是React 15或更低版本,它不支持在Render内部返回数组。你需要把你的东西包装在一个容器里。
import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import routes from './routes';
class RouterConfig extends Component {
render() {
return (
<div>{
routes.map((route) => {
return (
<Route
key={ route.id }
path={ route.path }
exact={ route.exact }
component={ route.component }
/>
);
})
}</div>
);
}
}
export default RouterConfig;
请注意包装Routes数组的div