首页 > 解决方案 > 在 react 和 redux 中使用 routerMiddleware 函数

问题描述

如何使用 routerMiddleware 将历史记录传递给 redux。我在下面尝试过但没有工作。我找不到任何集成 routerMiddleware 的资源。在这里,我正在尝试响应管理仪表板,它要求将历史记录作为道具传递给 redux 存储。所以我试图使用 routeMiddleware 来传递历史道具。

import { createStore, combineReducers, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
import { routerMiddleware, connectRouter } from 'connected-react-router'
import { createBrowserHistory } from 'history'
import { postListReducer } from './reducers/postReducers'

const history = createBrowserHistory()

const reducer = combineReducers({
  postList: postListReducer,
  router: connectRouter(history),
})

const initialState = { postList: { posts: [] } }

const middleware = [thunk, routerMiddleware(history)]

const store = createStore(
  reducer(history),
  initialState,
  composeWithDevTools(applyMiddleware(...middleware))
)

export default store

减速机:

import {
    POST_LIST_REQUEST,
    POST_LIST_SUCCESS,
    POST_LIST_FAIL,
    POST_CREATE_REQUEST,
    POST_CREATE_SUCCESS,
    POST_CREATE_FAIL,
  } from '../constants/postConstants'
  
  export const postListReducer = (state = { posts: [] }, action) => {
    switch (action.type) {
      case POST_LIST_REQUEST:
        return { loading: true }
      case POST_LIST_SUCCESS:
        return {
          loading: false,
          posts: action.payload,
        }
      case POST_LIST_FAIL:
        return { loading: false, error: action.payload }
      default:
        return state
    }
  }

标签: react-reduxconnected-react-router

解决方案


推荐阅读