关于将react-router 与 redux整合

2019-08-07  本文已影响0人  Mr君

why

react-router 与 redux的整合可以帮助我们实现:

how

  1. 安装connected-react-router 和 history :
npm install --save connected-react-router
npm install --save history
  1. 配置 store :
import thunk from 'redux-thunk'
import { createBrowserHistory } from 'history'

import { createStore, applyMiddleware } from 'redux'
import { connectRouter, routerMiddleware } from 'connected-react-router'

import reducers from '../reducers'

export const history = createBrowserHistory();  // 浏览器端应用可以使用createBrowserHistory来创建history对象
const initialState = {}

const store = createStore(
 connectRouter(history)(reducers), // 使用connectRouter包裹 root reducer 并且提供我们创建的history对象,获得新的 root reducer
 initialState,
 applyMiddleware(thunk, routerMiddleware(history)) // 使用routerMiddleware(history)实现使用 dispatch history actions,这样就可以使用push('/path/to/somewhere')去改变路由(这里的 push 是来自 connected-react-router 的)
)

export default store
  1. 配置根组件
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { ConnectedRouter } from 'connected-react-router'

import App from './App'
import store from './redux/store'
import { history } from './redux/store'

render(
  <Provider store={store}> // 使用ConnectedRouter包裹路由,并且将 store 中创建的history对象引入,作为 props 传入应用
    <ConnectedRouter history={history}> //ConnectedRouter组件要作为Provider的子组件
      <App />
    </ConnectedRouter>
  </Provider>,
  document.getElementById('app')
)
  1. 使用
    dispatch切换路由
import { push } from 'react-router-redux'
// Now you can dispatch navigation actions from anywhere!
store.dispatch(push('/about'))

可以看一个简单的例子

最后:
尽管这一问题官方文档中给出的是使用 react-router-redux但是该仓库已经不再维护,因而这里采用connected-react-routerhistoryreact-routerredux 进行深度整合。

上一篇 下一篇

猜你喜欢

热点阅读