首页 > 解决方案 > 在 redux 中调度操作的正确方法

问题描述

我的目标是调度一个动作,以便我可以传递我的状态对象。

import { addUser } from './actions' //action creator

this.state = {
  person: {
   name: '',
   age: 0,
  },
  isLoading: true,
}

//本地函数..

addNewUser = () => {
  //dispatches conditionally so the local func..
  this.props.addUser(this.state.person);
}

//派遣

mapDispatchToProps = dispatch => ({
  addUser: (person) => dispatch(addUser(person)),
})

错误显然在我的 mapDispatch 上(以错误的方式分配状态)。我该如何解决?(或者有更好的方法,但必须使用动作创建者)提前欣赏。

标签: reactjsreact-nativereduxreact-redux

解决方案


我发现将您的操作连接到您的导出和调用更简单,this.props.addUser因为它默认分配调度给它而无需做mapDispatchToProps

export default connect(
    mapStateToProps, 
    {action1, action2, addUser})(User)

那么你仍然可以使用:

addNewUser = () => {
  this.props.addUser(this.state.person);
}

然后在动作或减速器本身内完成其余的工作(取决于您对流程的偏好),例如:

export const addUser = user => ({
    type: ADD_USER_SUCCESS,
    payload: {user}
})

这确实更有用,因为从组件中执行逻辑更具可扩展性和可管理性。如果你有 10 个动作,它很快就会失控,你开始混合不同类型的逻辑。


推荐阅读