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

1. 由于 react-router 是集成了 react-router-dom 和 react-router-native的一起的,所以这里要使用的是 react-router-dom,

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

路由配置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组件,可以在用户访问某个路由时,跳转到其他路由:

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"/>,
]

 

posted @ 2019-06-10 18:03  小猪冒泡  阅读(1168)  评论(0编辑  收藏  举报