1

我想在 redux 中传递一个参数,但我没有找到方法。

这是我的代码:

还原/动作

export const next_page = (max_page) => {
    return {
        type: NEXT_PAGE,
        payload: max_page
    }
}

还原/中间件

export const update_page = (dispatch) => next => action => {
    next(action)
    if (action.type === NEXT_PAGE) {
      dispatch(next_page({max_page: action.payload}))
    } 
}

还原/减速器

export default (page = 1, action) => {
    switch (action.payload) {
        case NEXT_PAGE:
            const nextPage = page + 1
            return nextPage <= action.payload ? nextPage : page
        default:
            return page
    }
}

调用组件

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

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

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

export default connect(mapStateToProps, mapDispatchToProps)(Home)

ChangePage 组件

<button onClick={() => this.props.nextPage(max_page)}>Next</button>

问题是我不知道如何传递参数 max_page 以在 redux/reducer 中使用它

4

1 回答 1

1

你只需要max_page通过你的nextPage道具mapDispatchToProps

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

然后,当您在ChangePage组件内部调用它时,您的max_page参数将已经被传递。

另外,请注意,您不需要中间件来重新调度操作(这将导致无限循环):

// Just delete the middleware

你的减速器应该打开action.type,而不是action.payload

// redux/reducer
export default (page = 1, action) => {
    switch (action.type) { // changed from action.payload
        case NEXT_PAGE:
            const nextPage = page + 1
            return nextPage <= action.payload ? nextPage : page
        default:
            return page
    }
}
于 2019-08-21T13:19:43.420 回答