【问题标题】:ReactJs failing to bind data objectReactJs 无法绑定数据对象
【发布时间】:2017-03-30 16:40:58
【问题描述】:

我是 ReactJs 的新手,我正在尝试将 http 响应绑定到 DOM,但我无法让它工作。我使用 componentDidMount 来执行 api 调用。任何帮助将不胜感激,请参阅下面的代码。

var testStuff="First State";
var Test = React.createClass({
    loadTestData: function () {
        $.ajax({
            url: "http://localhost:64443/api/articles/apitest",
            type: 'GET',
            cache: false,
            dataType: 'json',
            success: function (response) {
                console.log(response);
                testStuff= response;
            },
            error: function (error) {
                alert(error);
            }
        });

    },
    componentDidMount() {
        this.loadTestData();
    },

    render() {
        console.log(this.testStuff);
        return (
          <div onClick={this.loadTestData}>
        {testStuff}
      </div>
    );
}
});
ReactDOM.render(
  <Test />,
  document.getElementById('content')
);

onClick 似乎在工作,但它几乎就像 componentDidMount 仅在页面呈现后才执行。

【问题讨论】:

    标签: reactjs react-jsx


    【解决方案1】:

    您需要在 AJAX 成功处理程序中正确更新组件状态:this.setState({ testStuff: data })

    然后您就可以在render 中使用this.state.testStuff 访问它。

    componentDidMount 实际上只在组件安装后运行。您还需要表示请求仍在进行中的 UI 状态(此时this.state.testStuff 将是undefined)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多