韩维 發表於 2020-5-26 15:43:00

react react-router-config

<div class="cnblogs_Highlighter">
<pre class="brush:javascript;gutter:true;">https://www.npmjs.com/package/react-router-config
</pre>
</div>
<p>  </p>
<p>这是我的目录,router文件 index.js 就是我的路由文件。 assembly 是引入组件的地方,那里配了懒加载</p>
<p><img src="https://img2020.cnblogs.com/blog/1896840/202005/1896840-20200526153849677-1102590190.png"></p>
<p>第一步: 安装</p>
<div class="cnblogs_Highlighter">
<pre class="brush:javascript;gutter:true;">npm install --save react-router-config
</pre>
</div>
<p>  </p>
<p>第二步: 外面&nbsp; index.js 引入</p>
<div class="cnblogs_Highlighter">
<pre class="brush:javascript;gutter:true;">import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import { persistStore } from 'redux-persist'   
import { PersistGate } from 'redux-persist/lib/integration/react';
import { renderRoutes } from "react-router-config";
import { BrowserRouter } from "react-router-dom";
import { store } from '@/store'
import routes from '@/router';//引入路由文件

ReactDOM.render(
&lt;Provider store={store}&gt;   {/* redux */}
    &lt;PersistGate loading={null} persistor={persistStore(store)}&gt;   {/* 数据持久化 */}
      &lt;BrowserRouter&gt;   {/* 路由 */}
      {renderRoutes(routes)}
      &lt;/BrowserRouter&gt;
    &lt;/PersistGate&gt;
&lt;/Provider&gt;,
document.getElementById('root')
)
</pre>
</div>
<p>  </p>
<p>第三步: router index.js 文件</p>
<div class="cnblogs_Highlighter">
<pre class="brush:javascript;gutter:true;">import { Home, Errors, Children01, Children02 } from './assembly';

const routes = [
{ path: '/404', component: Errors },
//嵌套路由
{ path: '/home', component: Home,
    routes: [
      { path: "/home/01", component: Children01 },
      { path: "/home/02", component: Children02 },
    ]
},
]

export default routes
</pre>
</div>
<p>  </p>
<p>第四步: home页面渲染子路由</p>
<div class="cnblogs_Highlighter">
<pre class="brush:javascript;gutter:true;">import React, { Component } from 'react'
import { renderRoutes } from 'react-router-config';
import { Link } from "react-router-dom";

export default class Home extends Component {
render() {
    const { routes } = this.props.route

    return (
      &lt;div&gt;
      &lt;Link to='/home/01'&gt;页面1&lt;/Link&gt;
      &lt;Link to='/home/02'&gt;页面2&lt;/Link&gt;
      {renderRoutes(routes)} //渲染子路由
      &lt;/div&gt;
    )
}
}
</pre>
</div>
<p>  </p><br><br>
来源:https://www.cnblogs.com/yetiezhu/p/12966026.html
頁: [1]
查看完整版本: react react-router-config