简体   繁体   English

React / redux - Onclick对reducer的反应

[英]React / redux - Onclick react to reducer

I have a react/redux application and I have the following challenge. 我有一个react / redux应用程序,我有以下挑战。 When I click on a button I want to save the form data and if a validation error occures in the backend I want to display and message and otherwise redirect. 当我单击一个按钮时,我想保存表单数据,如果在后端发生验证错误,我想显示和消息,否则重定向。

In my component I have this function 在我的组件中,我有这个功能

doSubmit = (data) => {
    const {actions, linkUtils, myObject} = this.props

    return actions.checkAuthentication()
      .then(actions.sendMyObject(myObject, data) )
        .then(linkUtils.openRoute('nextUrl'))
  }

Now the action uses dispatch to invoke the reducer and I can verify the reducer is invoked. 现在该操作使用dispatch来调用reducer,我可以验证是否调用了reducer。 I use action types and I use a switch case on the action type: 我使用动作类型,并在动作类型上使用switch case:

case types.SAVE_SUCCESS:
 return {
   ...state,
   save: true,
}
case types.SAVE_ERROR:
  return {
    ..state,
    saved: false,
    fieldErrors: action.payload.errors
}

Now in the doSubmit I would like something like this: 现在在doSubmit中我想要这样的东西:

return actions.checkAuthentication()
 .then(actions.sendMyObject(myObject, data) )
  .then( if (saved) { linkUtils.openRoute('nextUrl') } )

So that only when saving of the object is successful a redirect is done. 因此,只有在保存对象成功时才会进行重定向。

How can I do this? 我怎样才能做到这一点?

You could just switch on the data sendMyObject returns: 你可以直接打开sendMyObject返回的数据:

return actions.checkAuthentication()
  .then(actions.sendMyObject(myObject, data) )
    .then((saved) => {
      if (saved) {
        return linkUtils.openRoute('nextUrl');
      } else {
        // something else
      }
    });

For this to work, your promise sendMyObject needs to resolve saved or some other information telling the next promise in the chain whether or not it was successful. 为了实现这一点,您的promise sendMyObject需要解析已saved或其他一些信息,告知链中的下一个承诺是否成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM