用ajax设置react组件的初始状态

Set inital state of react component with ajax

本文关键字:初始状态 组件 react ajax 设置      更新时间:2023-09-26

我目前正在尝试用一些react组件来增强我的项目。我已经设法建立应用程序,它做我想要的。

现在我需要摆脱虚拟数组,其中包含一些数据和填充它与真实的数据从我的数据库。

通常我会使用ajax并解析它。

我已经检查了facebook文档,我发现了以下代码片段:

...    
componentDidMount: function() {
        $.get(this.props.source, function(result) {
          var lastGist = result[0];
          if (this.isMounted()) {
            this.setState({
              username: lastGist.owner.login,
              lastGistUrl: lastGist.html_url
            });
          }
        }.bind(this));
      },
...

现在我的问题是,如何以及何时应该在react组件中调用这个函数。或者它是一个保存的名称并自动调用?

谢谢你

是保存的名称并自动调用吗?

是的。

https://facebook.github.io/react/docs/component-specs.html mounting-componentdidmount