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

前端之家收集整理的这篇文章主要介绍了reactjs – React-router-dom v4嵌套路由不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
关于未解决的问题(作为最终结论)

> Multiple Nested Routes in react-router-dom v4
> How to nest routes in React Router v4?

我也遇到了同样的问题.

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

此外,人们发现在一个文件中而不是在组件内列出路径更好.

提到的东西: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,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;

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

> / login没有页眉或页脚.> /,/ list和/ settings都有页眉和页脚.>任何未找到的路径都将显示PageNotFound组件,没有页眉或页脚.

原文链接:https://www.f2er.com/react/301073.html

猜你在找的React相关文章