如何简化mapDispatchToProps中的多个dispatch调用?Redux-thunk是否可行?
结论
这种写法完全可行,Redux-thunk刚好可以帮你实现这个需求。
实现原理
你原来的draw逻辑写在mapDispatchToProps里,需要依赖组件从mapState拿到的board、players状态,所以每次调用都要传三个参数。改用Redux-thunk之后,你可以把draw封装成thunk类型的action creator,直接在内部从store获取需要的状态,不需要组件额外传状态参数。
具体实现步骤
- 先封装thunk版的
drawaction creator:
const draw = (squareIndex) => { // redux-thunk会自动给返回的函数注入dispatch和getState两个参数 return (dispatch, getState) => { // 直接从store中取需要的board和players状态,不用依赖组件传参 const { board, players } = getState(); if (!board[squareIndex]) { if (players[players.turn] === 'X') { dispatch(drawX(squareIndex)); } else { dispatch(drawO(squareIndex)); } dispatch(checkResult()); dispatch(toggleTurn()); } } }
- 简化
mapDispatchToProps写法:
你甚至不需要写函数形式的mapDispatchToProps,直接传对象即可,Redux会自动把对象里的action creator包一层dispatch:
const mapDispatchToProps = { draw }
如果要保留你写的函数形式,也可以写成你想要的效果:
const mapDispatchToProps = dispatch => ({ draw })
- 组件内调用方式:
现在组件里调用draw只需要传squareIndex一个参数即可:
// 比如方块点击事件的回调 onClick={() => props.draw(squareIndex)}
内容的提问来源于stack exchange,提问作者Kate
相关产品推荐
相关产品推荐

