React之路由的使用及路由懒加载

//1、安装react-router-dom
yarn add react-router-dom
//2、在使用路由的页面引入
import {HashRouter,Link,Router,Switch, Route, Redirect} from 'react-router-dom'
//HashRouter最外层必须由它包裹
//Link用于点击跳转
//Switch路由唯一匹配
//Route配置路由规则
//Redirect跳转错误显示的页面

完整代码(这里是将路由单独一个组件,然后引入到App组件中)

import React from 'react'
import {HashRouter,Link,Router,Switch, Route, Redirect} from 'react-router-dom'
import City from '@/pages/city'
import Home from '@/pages/home'
import Login from '@/pages/login'
import User from '@/pages/user'

export default ()=>{
    return(
        <HashRouter>
	        <Switch>
	            <Route path='/' exact component={Home}></Route>/*exact精确匹配,如果不加,下
	            												面所有页面都会匹配到Home页面*/
	            <Route path='/city' component={City}></Route>
	            <Route path='/login' component={Login}></Route>
	            <Route path='/user' component={User}></Route>
	            <Redirect to='/'></Redirect>
	        </Switch>
        </HashRouter>
    )
}

路由懒加载
主要是页面组件的引入和在switch外面加了个suspense

import React,{ Suspense, lazy } from 'react'
import {HashRouter,Link,Router,Switch, Route, Redirect} from 'react-router-dom'
const Home = lazy(() => import('@/pages/home'));//这里改变了
const City = lazy(() => import('@/pages/city'));
const Login = lazy(() => import('@/pages/login'));
const User = lazy(() => import('@/pages/user'));

export default ()=>{
    return(
        <HashRouter>
            <Suspense fallback={<div>Loading...</div>}>//这里改变了
                <Switch>
                    <Route path='/' exact component={Home}></Route>
                    <Route path='/city' component={City}></Route>
                    <Route path='/login' component={Login}></Route>
                    <Route path='/user' component={User}></Route>
                    <Redirect to='/'></Redirect>
                </Switch>
            </Suspense>
        </HashRouter>
    )
}

你可能感兴趣的:(react)