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"/>}} exact/>, <Route path="/list" component={TopicList} />, <Route path="/detail" component={TopicDetail}/>, ]
原文地址:https://www.cnblogs.com/xiaozhumaopao/p/10999322.html
时间: 2024-11-10 04:45:01