react-路由

99 阅读1分钟

react中使用路由,BrowserRouter, Switch, Route, Redirect 这是基本路由组件。

配置懒加载,借助lazy,Suspense。路由跳转使用Link/NavLink,或者props.history.push('/login')。

props中的参数:

history: {length: 5, action: 'PUSH', location: {}, createHref: ƒ, push: ƒ, }

location: {pathname: '/', search: '', hash: '', state: undefined}

match: {path: '/', url: '/', isExact: true, params: {}}

staticContext: undefined

使用:

yarn add react-router-dom@5
import {lazy,Suspense} from 'react';
import {BrowserRouter, Switch, Route, Redirect} from "react-router-dom";

import './App.css';

const Login = lazy(()=> import('./pages/login'))
const Admin = lazy(()=> import('./pages/admin'))

function App() {
  return (
    <Suspense fallback={<h1></h1>}>
      <BrowserRouter>
        <Switch>
          <Route path="/login" component={Login}></Route>
          <Route path='/' component={Admin}></Route>
          <Redirect to="/"/>
        </Switch>
      </BrowserRouter>
    </Suspense>
  );
}

export default App;

解决history模式404

node服务器,下载 npm i connect-history-api-fallback

捕获.PNG