webpack 配置react腳手架(四):路由配置

1. 因爲 react-router 是集成了 react-router-dom 和 react-router-native的一塊兒的,因此這裏要使用的是 react-router-dom,react

2. 安裝  npm i react-router -S 、 npm i react-router-dom -S npm

路由配置router.js:數組

import React from 'react'
import {
  Route
} from 'react-router-dom'

import TopicList from '../views/topic-list/index'
import TopicDetail from '../views/topic-detail/index'

export default () => [ 
//react 16 能夠直接返回一個數組 不須要在外層加div /* 這裏路由爲 ‘/’ 的要加上 exact。由於/路由最大,覆蓋了/detail 等路由,不加設置的話, 全部的頁面都會同時加載 / 的路由內容,因此加上 exact,規定只能嚴格等於該路由。 */ <Route path="/" component={TopicList} exact/>, <Route path="/detail" component={TopicDetail} key="detail" />, ]

對於最外層的入口文件 app.js瀏覽器

import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter } from 'react-router-dom' //瀏覽器路由
import { AppContainer } from 'react-hot-loader' // eslint-disable-line
import App from './views/App'//組件

const root = document.getElementById('root')
const render = (Component) => {
  ReactDOM.hydrate(
    <AppContainer>
        <BrowserRouter>
            <Component /> 
        </BrowserRouter>
    </AppContainer>,
    root,
  )
}

render(createApp(App))

if (module.hot) {
  module.hot.accept('./views/App', () => {
    const NextApp = require('./views/App').default // eslint-disable-line 
    render(createApp(NextApp))
  })
}

使用 Redirect組件,能夠在用戶訪問某個路由時,跳轉到其餘路由:react-router

import React from 'react'
import {
  Route,
  Redirect,
} from 'react-router-dom'

import TopicList from '../views/topic-list/index'
import TopicDetail from '../views/topic-detail/index'

export default () => [ 
  <Route path="/" render={()=>{ <Redirect to ="/list"/>}} key="index"  exact/>,
  <Route path="/list" component={TopicList} key="list"/>,
  <Route path="/detail" component={TopicDetail} key="detail"/>,
]
相關文章
相關標籤/搜索