在ReactJS中调用ajax后更新变量?

时间:2017-07-18 20:53:58

标签: javascript ajax reactjs

我有一个方法可以在用户更改状态时从api获取页面数据(使用public CatSubCatList GenerateCategoryListFromProductFeedXML() { string path = System.Web.HttpContext.Current.Server.MapPath(_xmlFilePath); XDocument xDoc = XDocument.Load(path); XElement xElement = XElement.Parse(xDoc.ToString()); List<Category> lstCategory = xElement.Elements("Product").Select(d => new Category { Code = Convert.ToString(d.Element("CategoryCode").Value), CategoryPath = d.Element("CategoryPath").Value, Name = GetCateOrSubCategory(d.Element("CategoryPath").Value, 0), // Category SubCategoryName = GetCateOrSubCategory(d.Element("CategoryPath").Value, 1) // Sub Category }).GroupBy(x => new { x.Code, x.SubCategoryName }).Select(x => x.First()).ToList(); CatSubCatList catSubCatList = GetFinalCategoryListFromXML(lstCategory); return catSubCatList; } )。一些页面具有需要第二次ajax调用以获取更多数据的属性。我遇到的问题是变量没有使用辅助信息进行更新。我理解“为什么”而不是如何解决它。

react-route-dom

我已经//page data gets pulled into a state and passed to a child component "page.js" //gets archive attribute var isArchive = customMeta.isArchive; //gets the archive target name var archiveName = customMeta.archiveName; //sets the initial value (mostly for debugging) var worksArchive = "hello world"; //checks if value exists and that it is an archive if(isArchive && isArchive == "true"){ //only get the archive info if the name is also present if(customMeta.archiveName) { //make the ajax call to get the data for the archive pages axios.get('http://admin.datasite.co/v2/'+archiveName) .then((response) => { var archivePages = response.data; //if the archive is "works" then create a list of archive pages if(archiveName == "works"){ //run a loop for each page returning a link that passes through a history router worksArchive = archivePages.map(function(work){ return <Link key={work.id} className="work-item" to="/" ><img src={work.post_meta.targetimg} /></Link>; }); } }) .catch((error) => { console.log(error); }); } } ... {worksArchive} //this always outputs "hello world" ... 浏览了ajax和console.log,一切都正确无误。我知道问题是在绘制dom后再次设置值,这就是为什么我没有看到更改。我认为他们的方法是将其保存为状态但不确定如何解决问题。

2 个答案:

答案 0 :(得分:1)

让您的worksArchive处于组件状态,并使用setState进行更新。

class MyComponent extends React.Component{
    constructor(){
        super();
        this.state = {
            worksArchive: "hello world" //initial value
        }
    }
    ...
    //in axios then
        var newWorksArchive = archivePages.map(function(work){
            return <Link key={work.id} className="work-item" to="/" ><img src={work.post_meta.targetimg} /></Link>;
        });
        this.setState({worksArchive: newWorksArchive});
    ...
}

答案 1 :(得分:0)

与州合作。将archivePages存储为空数组并进行渲染,然后在设置状态后,组件将重新渲染,因为状态已更新。以下是您将如何处理它的示例。

&#13;
&#13;
class TestComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      archivePage: []
    };
  }
  componentDidMount() {

    //gets archive attribute
    var isArchive = customMeta.isArchive;
    //gets the archive target name
    var archiveName = customMeta.archiveName;
    //sets the initial value (mostly for debugging)
    var worksArchive = "hello world";

    //checks if value exists and that it is an archive
    if (isArchive && isArchive == "true") {
      //only get the archive info if the name is also present
      if (customMeta.archiveName) {
        //make the ajax call to get the data for the archive pages
        axios.get("http://admin.datasite.co/v2/" + archiveName)
          .then(response => {
            var archivePages = response.data;

            //if the archive is "works" then create a list of archive pages
            if (archiveName == "works") {
              //run a loop for each page returning a link that passes through a history router
              this.setState({
                  archivePages: archivePages
              })
            }
          })
          .catch(error => {
            console.log(error);
          });
      }
    }

  }
  render() {
    return (
      <div>
        {this.state.archivePages.map(work => {
          return (
            <Link key={work.id} className="work-item" to="/">
              <img src={work.post_meta.targetimg} />
            </Link>
          );
        })}
      </div>
    );
  }
}
&#13;
&#13;
&#13;