在ajax成功中反应状态更新

时间:2018-04-17 06:23:42

标签: ajax reactjs setstate

成功运行ajax调用时,我遇到设置状态的问题。我想在ajax进程完成时更新状态。 div中的文本保持“Busy”而不是“Done”,而在浏览器Network选项卡中,我看到状态从“pending”变为“200”状态。

import React, { Component } from "react";
import * as ReactDOM from "react-dom";
import { extend } from "lodash";

export class StoreToCheck extends React.Component{
  constructor(props){
    super(props);
    this.state = { ListWithISBN :[],
                   getISBNS : false };
    this.ajaxSuccess = this.ajaxSuccess.bind(this);
  }
  getISBNSList(){
    if(!this.state.getISBNS){
      var store_name;
      // loop through array to fill store_name variable

      var ajaxSuccess = this.ajaxSuccess;
      if(store_name != ''){
        apex.server.process(
          'GET_EBOOKS_FROM_STORE',
          {
            success:function (data){
              // when succesfull update state getISBNS
              ajaxSuccess
            }
          }
        );
      }
    }
  }
  ajaxSuccess(){
    this.setState({"getISBNS":true});
  }
  componentDidMount(){
    this.getISBNSList();
  }
  render(){
    return(
      <div>
          {this.state.getISBNS ? "Done" : "Busy"}
      </div>
    )
  }
}

1 个答案:

答案 0 :(得分:2)

您需要使用call ajaxSuccess方法,而不是存储正确的函数引用,您可以将其绑定到位

getISBNSList(){
    if(!this.state.getISBNS){
      var store_name;
      // loop through array to fill store_name variable

      if(store_name != ''){
        apex.server.process(
          'GET_EBOOKS_FROM_STORE',
          {
            success: (data) => { // bind here with arrow function
              // when succesfull update state getISBNS
              this.ajaxSuccess() // call the function
            }
          }
        );
      }
    }
  }