gpt4 book ai didi

javascript - react 未找到组件总是呈现

转载 作者:行者123 更新时间:2023-12-03 13:54:08 26 4
gpt4 key购买 nike

这是循环遍历路由文件的代码。在这里,我正在创建 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;

This is my route configuration file, where i have listed all routes.

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;

This is my app.js import React, { Component } from 'react'; import { Switch, Router, Route } from 'react-router-dom'; import Header from '../header/header'; import Footer from '../footer/footer'; import history from '../../history'; import RouterConfig from '../../router/browserroute';

class App extends Component {
render() {
return (
<div>
<Router history={ history } >
<div>
<Header />
<Switch>
<RouterConfig />
</Switch>
<Footer />
</div>
</Router>
</div>
);
}
}

export default App;

issue is on every page i am getting not found component render. Even using switch with routes not getting the expected results. not sure why code is not working properly.

[this is how it renders not found in every page ][1]

[1]: /image/B7evW.png

on changing:

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>
);
}
}

这很好用

最佳答案

您需要将Switch移动到RouteConfig内部。 React 16 部分的工作方式一定有一些在 React Router 中意想不到的东西(我不太确定为什么当 Switch 位于 RouterConfig 之外时它不起作用)。好消息是,至少对我来说,在 RouteConfig 中是有意义的。

这是一个有效的codesandbox:

https://codesandbox.io/s/8xmx478kq8

关于javascript - react 未找到组件总是呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46577443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com