reactjs – React和Flux:“在调度中间调度”以显示来自API调用的错误消息

前端之家收集整理的这篇文章主要介绍了reactjs – React和Flux:“在调度中间调度”以显示来自API调用的错误消息前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用Flux,React和我有组件简单和消息:

>简单:它是一个通过Action调用API的简单组件. Action执行ajax请求并在jqXHR.done()中调度结果.简单有一个更改侦听器等待调度结果.如果结果为null,我想使用我的Messages组件显示错误,所以我调用了MessagesAction.addError(‘我的结果是null’).
>消息:显示应用程序错误的组件.此组件具有更改侦听器,等待显示新消息.它放在我的应用程序的标题中.

当我收到null结果并立即调用Simple组件内的MessagesAction.addError时,会出现问题.事实上,我知道这可能会导致“在调度中间发送”错误,但我不知道如何重构此代码显示使用Flux的错误消息.

免责声明1:我无法使用setTimeout函数解决此问题.这不是正确的解决方案.

免责声明2:Simple组件代表app中的任何其他组件,它也将使用Messages组件显示消息.

简单代码

  1. findUser: function (value) {
  2. UserAction.find(value);
  3. },componentDidMount: function () {
  4. UserStore.addChangeListener(this.updateUser);
  5. },updateUser: function(){
  6. var user = UserStore.getUser();
  7. if (user == null){
  8. MessagesAction.addError('My result is null!'); //here occur the error!
  9. } else {
  10. //set my user with setState
  11. }
  12. },

消息代码

  1. componentDidMount: function () {
  2. MessagesStore.addChangeListener(this.addMessage);
  3. },addMessage: function () {
  4. this.setState({
  5. messages: MensagensStore.getMessages()
  6. });
  7. },

谢谢!

好吧,问题是(至少在Facebook的Dispatcher实现中)你不能在商店回调中触发任何动作,这会导致不希望的/不可预测的行为,如无限调度或不一致的状态变化(例如竞争条件).这是由于单个广播调度员的性质.

IMHO最干净的解决方案(没有闻到waitFor())是在触发组件中引入内部状态.使用状态可以在下一个更新周期中触发消息操作.这样,您就不会遇到未完成调度的问题.

  1. // your component's implementation
  2.  
  3. getInitialState : function(){
  4. return { user : undefined };
  5. }
  6.  
  7.  
  8. componentWillMount: function () {
  9. UserStore.addChangeListener(this.updateUser);
  10. },componentWillUnmount: function () {
  11. UserStore.removeChangeListener(this.updateUser);
  12. },componentDidUpdate : function(){
  13. if(this.state.user == null){
  14. MessagesAction.addError('My result is null!'); // no error anymore!
  15. }
  16. },updateUser: function(){
  17. this.setState({ user: UserStore.getUser(); });
  18. },

猜你在找的React相关文章