第一步:安装react-router-dom
npm install react-router-dom
然后单独在src
下建立router
文件夹进行路由配置
在 src/router
下建立index.js
进行路由配置
import React from 'react'
import loadable from 'loadable-components' //npm i loadable-components 用作解决路由懒加载
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import NotFound from '../containers/notFound/notFound'
const Loading = () => <div>Loading...</div>
const Home = loadable(() => import('../containers/home/home'), {
LoadingComponent: Loading,
})
const Login = loadable(() => import('../containers/login/login'), {
LoadingComponent: Loading,
})
class IRouter extends React.Component {
render() {
return (
<Router>
<Switch>
<Route path="/login" component={Login} />
<Route path="/" exact component={Home} />
{/* 404页面 */}
<Route path="*" component={NotFound} />
</Switch>
</Router>
)
}
}
export default IRouter
查看其它博客看到很多用
import Loadable from 'react-loadable' //此处安装使用 npm install react-loadable 进行安装
进行懒加载,但是项目会报错警告,于是我改成了 (loadable-components官方文档)
import loadable from 'loadable-components' //npm i loadable-components 用作解决路由懒加载
最后再修改src项目的index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Router from './router/index'
ReactDOM.render(
<React.StrictMode>
<Router />
</React.StrictMode>,
document.getElementById('root')
);
项目结构