【问题标题】:React state update in ajax success在ajax成功中反应状态更新
【发布时间】:2018-09-27 00:19:49
【问题描述】:

当成功运行 ajax 调用时,我在设置状态时遇到问题。我想在 ajax 进程完成时更新状态。 div 中的文本保持在“忙碌”而不是“完成”,而在浏览器网络选项卡中,我看到状态从“待定”变为状态“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>
    )
  }
}

【问题讨论】:

  • 我不认为这是重复的。提供的代码有编码错误。错误是您需要在成功函数中调用函数 ajaxSuccess,例如 ajaxSuccess();提供的代码不会调用该函数,因为它缺少成功函数内函数名称末尾的括号
  • 你是对的。盯着代码看了好久才发现少了(),哈哈谢谢!

标签: ajax reactjs setstate


【解决方案1】:

你需要callajaxSuccess方法,也不是存储正确的函数引用,你可以就地绑定它

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
            }
          }
        );
      }
    }
  }

【讨论】:

    猜你喜欢
    • 2022-12-10
    • 2016-08-07
    • 1970-01-01
    • 2022-01-21
    • 2022-01-23
    • 2018-09-29
    • 2018-03-28
    • 1970-01-01
    相关资源
    最近更新 更多