首页 > 解决方案 > 使用 applyMiddleware,调度不起作用

问题描述

您好,我是 redux 的新手,我没有看到问题,我查看了其他 stackoverflow,有类似的问题,但没有找到我的问题。问题是调度不起作用。

src/redux/index.js

export default combineReducers({
    page: pageReducer,
    fetch: fetchReducer
})

src/index.js

import allReducer from './reducers'
import { pageMd1 } from './reducers/middleware/page'
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { Provider } from 'react-redux'

const store = createStore(
    allReducer,
    applyMiddleware(thunk)
)

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>, 
    document.getElementById('root'));

src/redux/动作

export const PREVIOUS_PAGE = 'PREVIOUS_PAGE'

export const previous_page = (max) => {
    return {
        type: PREVIOUS_PAGE,
        payload: max
    }
}

src/redux/中间件

import { PREVIOUS_PAGE, previous_page } from '../actions'

export const update_page = ({dispatch}) => next => action => {
    next(action)
  
    if (action.type === PREVIOUS_PAGE) {
      dispatch(previous_page({max: action.payload}))
    }
  }

  export const pageMd1 = [ update_page ]

src/redux/reducer

import { NEXT_PAGE, PREVIOUS_PAGE } from './actions'

export default (state = 1, action) => {
    console.log('reducer')
    switch (action.type) {
        case NEXT_PAGE:
            return state + 1
        case PREVIOUS_PAGE:
            return state - 1
        default:
            return state
    }
}

源/首页

<ChangePage max={this.state.max_pages} {...{prevPage, nextPage}} />

const mapStateToProps = state => ({
  page: state.page
})

const mapDispatchToProps = (dispatch) => ({
  prevPage: () => dispatch(previous_page),
  nextPage: () => dispatch(next_page),
})

export default connect(mapStateToProps, mapDispatchToProps)(Home)

源/更改页面

<button className='SelectionOff' id='decrement' onClick={() => this.props.prevPage(max_page) }>Previous</button>

希望很明确......问题是调度不起作用

标签: reduxreact-redux

解决方案


你需要调用里面的函数dispatch

const mapDispatchToProps = (dispatch) => ({
  prevPage: () => dispatch(previous_page()),
  nextPage: () => dispatch(next_page()),
})

推荐阅读