不能派遣中间派遣 [英] Cannot dispatch in the middle of a dispatch

查看:299
本文介绍了不能派遣中间派遣的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我得到的错误是:

pre $ $ code未被捕获(承诺)错误:不变违规:Dispatch.dispatch(.. (...)

我读过无数次关于这个错误的帖子,但我似乎无法弄清楚为什么我得到它。我得到页面加载错误,从这上面工作正常。当我删除加载动作:加载:StudentsActions.studentsLoading 它一切正常。



你可以找到所有的代码在 github回购



预先感谢!

解决方案

你得到这个错误是因为你同时执行多个调度。当页面加载时,你的 NavBar 组件和你的 StudentList 组件都被渲染,调用 componentDidMount ,在你的情况下你在这两个地方发起一个调度。



组件与您的调度程序/商店进行交互。正如在flux文档中指出的那样,正确的方法是通过道具将一个单独的顶级组件句柄分发并传递给其他组件。在你的情况下,应用程序组件是唯一应该知道的商店或可以派遣行动。



<这有很多优点,例如使整个应用程序更易于使用和重构,因为大多数组件不知道或关心数据的来源。这也将防止你得到的错误。流量不允许同时发送多个调度的原因是因为允许它会导致您不清楚为什么您的应用程序处于特定状态。不再有一行逻辑可以用来确定你的应用程序在做什么。


So the error I get is:

Uncaught (in promise) Error: Invariant Violation: Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.(…)

I've read through countless of posts regarding this error but I can't seem to figure out why I get it. I get the error at pageload, from thereon it works fine. When I remove the loading action: loading: StudentsActions.studentsLoading it all works fine.

You can find all the code on the github repo

Thanks in advance !

解决方案

You are getting this error because you perform multiple dispatches at the same time. When the page loads, your NavBar component and your StudentList component are both rendered, which invokes componentDidMount on both, and in your case you initiate a dispatch in both places.

You are using a bad flux pattern by having "presentation" components interact with your dispatcher/stores. The correct approach, as pointed out in the flux documentation, is to have a single, top-level component handle dispatches and pass down state to other components via props. In your case, the App component is the only one that should be aware of the stores or that can dispatch actions.

This has many advantages, such as making your entire application far easier to use and refactor since most components don't know or care where the data comes from. It will also prevent the error you're getting. The reason flux does not allow multiple dispatches at the same time is because allowing it would lead to situations where it's unclear why your application is in a particular state. There is no longer a single line of logic that can be followed to determine what your application is doing.

这篇关于不能派遣中间派遣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆