React-Router
在react
中,Router
是一个组件,在任何地方都可以使用。但是为了代码结构的整洁,我们一般把Router
做为容器性组件处理。
配置Router
安装
yarn add react-router react-router-dom history react-router-redux //or npm i react-router react-router-dom history react-router-redux
关联redux
我们知道一个工程只有一个
store
,而且由store
来管理整个工程的state
,所以必须将router
交给store
来管理。import { routerReducer, routerMiddleware } from 'react-router-redux'; import { createBrowserHistory } from 'history'; import { applyMiddleware } from 'redux'; import Reducer from '../reducers/Index'; const history = createBrowserHistory(); createStore( combineReducers({ ...Reducer, routing: routerReducer }), applyMiddleware(routerMiddleware(history), createLogger()) )
- 加入Router
import React from 'react'; import ReduxConfig from '../store/Store'; import { Provider } from 'react-redux'; import { Router } from 'react-router' const { history, store } = ReduxConfig; export default ({ children }) => <Provider store={store}> <Router history={history}> {children} </Router> </Provider>
Link
类似
a
标签,提供一个超链接。<Link to={'/home'} >Go Home</Link>
跳转到指定页面
有时候无法在表现性组件中使用
Link
时,可以使用history
来跳转。import {push} from 'react-router-redux'; dispatch => { dispatch(push('/home')); };