使用applyMiddleware,调度无法正常工作

时间:2019-08-21 09:54:34

标签: redux react-redux

你好,我是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 / actions

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
    }
}

src / Home

<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)

src / ChangePage

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

希望很清楚...问题是调度无法正常工作

1 个答案:

答案 0 :(得分:1)

您需要在dispatch内部调用该函数:

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