reactjs - 在 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 上(以错误的方式分配状态)。我该如何解决?(或者有更好的方法,但必须使用动作创建者)提前欣赏。
解决方案
我发现将您的操作连接到您的导出和调用更简单,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 个动作,它很快就会失控,你开始混合不同类型的逻辑。
推荐阅读
- python - 按键切片字典列表时出错?
- mysql - 从 Node.js Cloud Function 插入到 Google Cloud SQL
- java - 为什么当它与我的正则表达式匹配时这个布尔值没有改变?
- asp.net-mvc - 如何在不使用 model.Count 的情况下获取 Viewbag 的计数
- android - AOSP 我的应用程序未包含在系统构建中
- php - 在 laravel 中使用多个参数的路由会破坏其他参数
- html - 在电子邮件模板的下一行全宽显示表格单元格
- python - 如何遍历具有条件的列中的每个值并创建具有新值的新列
- reactjs - 如何设置列表中的项目
- excel - 从多个 CSV 文件构建 Excel 电子表格