[英]react not found component always renders
這是循環路由文件的代碼。 在這里我創建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,來自'react'的{Component}; 從'react-router-dom'導入{Switch,Router,Route}; 從'../header/header'導入標題; 從'../footer/footer'導入頁腳; 從'../../history'導入歷史記錄; 從'../../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? 如果您使用的是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
您需要將Switch
移動到RouteConfig
。 必須有一些React 16部分工作的方式在React Router中是意外的(我不確定為什么當Switch在RouterConfig之外時它不起作用)。 好消息是,至少在我看來,進入RouteConfig是有道理的。
這是一個有效的代碼框:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.