gpt4 book ai didi

reactjs - React-router-dom v4 嵌套路由不起作用

转载 作者:行者123 更新时间:2023-12-03 13:17:41 24 4
gpt4 key购买 nike

引用 Unresolved 问题(作为最终结论)

我也遇到同样的问题

https://reacttraining.com/react-router/web/guides/quick-start促销react-router-dom

此外,人们发现更好的 list down routes在一个文件中而不是在组件内。

引用内容: https://github.com/ReactTraining/react-router/tree/master/packages/react-router-config

有效的东西(大部分):

import * as React from 'react'
import {BrowserRouter as Router, Route, Switch } from 'react-router-dom'


export const Routes = () => (
<Router>
<div>
<Switch>
<Route exact path="/login" component={Login}/>
<MainApp path="/">
<Route path="/list" component={List}/>
<Route path="/settings" component={Settings}/>
</MainApp>
<Route path="*" component={PageNotFound}/>
</Switch>
</div>
</Router>
)

有些东西不起作用: site.com/SomeGarbagePath显示<MainApp>我想。
<Route path="*" component={PageNotFound}/>

更新

/ - Home - parent of all (almost)
/List - inside home
/Settings - inside home
/Login - standalone
/Users - inside home, For now just showing itself. It has further pages.
/User/123 - inside user with /:id
/User/staticUser - inside user with static route
/garbage - not a route defined (not working as expected)

最佳答案

这是执行您所描述的操作的一种方法(请注意,还有其他方法可以直接在 React 组件中处理布局)。为了使示例保持简单,其他组件(<Home>, <List> 等)被创建为纯功能组件,没有属性或状态,但将每个组件作为正确的 React 组件放入自己的文件中将是微不足道的。下面的示例已完成并将运行。

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

class App extends Component {
render() {

const Header = () => <h1>My header</h1>;
const Footer = () => <h2>My footer</h2>;
const Login = () => <p>Login Component</p>;
const Home = () => <p>Home Page</p>;
const List = () => <p>List Page</p>;
const Settings = () => <p>Settings Page</p>;
const PageNotFound = () => <h1>Uh oh, not found!</h1>;

const RouteWithLayout = ({ component, ...rest }) => {
return (
<div>
<Header />
<Route {...rest} render={ () => React.createElement(component) } />
<Footer />
</div>
);
};

return (
<Router>
<div>
<Switch>
<Route exact path="/login" component={Login} />
<RouteWithLayout exact path="/" component={Home} />
<RouteWithLayout path="/list" component={List} />
<RouteWithLayout path="/settings" component={Settings} />
<Route path="*" component={PageNotFound} />
</Switch>
</div>
</Router>
);
}
}

export default App;

这将执行以下操作,希望这就是您问题中现在描述的内容:

  1. /login没有页眉或页脚。
  2. / , /list ,和/settings都有页眉和页脚。
  3. 任何未找到的路线都会显示 PageNotFound组件,没有页眉或页脚。

关于reactjs - React-router-dom v4 嵌套路由不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43309710/

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