weixin_33696106 2018-11-27 14:11 采纳率: 0%
浏览 186

React / Redux表单提交

In my application, I am using actions to do all of my ajax calls. When the results come back, it dispatches them to the reducer, which then puts it in the store. My component is bound to the property and will then be able to get it from the store.

However, I am having an issue trying to figure out the best way to do form submissions. From a listing page, a user can click on a link from any row to open a modal. This modal has a form in it. When the form is filled out, it will then pass the data along to an action, which will submit it. The only response from a valid submission is a HTTP 200.

Without using callbacks, how would the modal know that the ajax call is complete, so it can close itself? As of now, I have a flag in the store called form.processing. This is default to false, and the action will set it to true when it begins and false when its done. The component watches this and then knows when it goes from true to false and knows everything is done. However, I feel like there should be a better way.

Or should I be using callback in forms, even though we don't follow that process for any other ajax call?

  • 写回答

1条回答 默认 最新

  • local-host 2018-11-27 14:35
    关注

    Here are following pseudo code can help you:

     constructor () {
         this.state = {
             disaplyModalPopup: false;
         }
     }
    
     handleSubmit = () => {
        this.setState({disaplyModalPopup: true})
        let payLoad = { 'Key':this.state.something }
        this.props.hitAPI(payLoad).then((res) => {
          if (res.data.success) {
            this.setState({
                'disaplyModalPopup': false
            })
          }else{
              this.setState({
                'disaplyModalPopup': true,
                'errorMessage': 'something wend wrong'
            })
          }
        })
     }
    
     rendor (){
         let errorMessage = {this.state.errorMessage}
         let disaplyModalPopup = {this.state.disaplyModalPopup}
         return (
             {disaplyModalPopup ? <modal> </modal> : ''}
             { errorMessage? 'errorMessage': ''}
         )
     }
    

    Here I have handled your modalPopup with disaplyModalPopup state. And After get in the response saved in reducer, it is changes as {disaplyModalPopup: false} And modalPopUp HTML will disappear.

    But in case your API get in failed while making response. So that case: i have handle as error message in as text errorMessage where you can show your error message. So that Modal is closed side by side.

    评论

报告相同问题?