React抛出错误:不能读取property 'map'的定义

React throwing error: Cannot read property 'map' of undefined

本文关键字:map 定义 property 读取 出错 错误 不能读 不能 React      更新时间:2023-09-26

我正在学习React。我正在阅读书中的一章,其中他们从componentDidMount下的API加载数据,并将组件的状态更新为

getInitialState: function () {
      return {changeSets: []};
   },
   mapOpenLibraryDataToChangeSet : function (data) {
    return data.map(function (change, index) {
      return {
        "when":jQuery.timeago(change.timestamp),
        "who": change.author.key,
        "description": change.comment
      }
    });
  }, 
  componentDidMount: function () {
        $.ajax({
            url: 'http://openlibrary.org/recentchanges.json?limit=10',
            context: this,
            dataType: 'json',
            type: 'GET'
        }).done(function (data) {
//             console.log(data);
            var changeSets = this.mapOpenLibraryDataToChangeSet(data);
            console.log("changeSets:" + JSON.stringify(changeSets));
            this.setState({changeSets: changeSets});
        });
    },

当我运行这个时,我在控制台看到错误

"TypeError: Cannot read property 'map' of undefined
    at t.render (mikobuf.js:55:41)
    at _renderValidatedComponentWithoutOwnerOrContext (https://npmcdn.com/react@15.3.1/dist/react.min.js:13:17508)
    at _renderValidatedComponent (https://npmcdn.com/react@15.3.1/dist/react.min.js:13:17644)
    at performInitialMount (https://npmcdn.com/react@15.3.1/dist/react.min.js:13:13421)
    at mountComponent (https://npmcdn.com/react@15.3.1/dist/react.min.js:13:12467)
    at Object.mountComponent (https://npmcdn.com/react@15.3.1/dist/react.min.js:15:2892)
    at h.mountChildren (https://npmcdn.com/react@15.3.1/dist/react.min.js:14:26368)
    at h._createInitialChildren (https://npmcdn.com/react@15.3.1/dist/react.min.js:13:26619)
    at h.mountComponent (https://npmcdn.com/react@15.3.1/dist/react.min.js:13:24771)
    at Object.mountComponent (https://npmcdn.com/react@15.3.1/dist/react.min.js:15:2892)"

运行链接为http://jsbin.com/mikobuf/edit?js,console,output

我做错了什么?

当我在渲染应用程序时添加changeSets={data}时,我在控制台看到数据

ReactDOM.render(<App headings = {headings} changeSets={data}/>, document.getElementById("container"))

但是我想从API中提取数据。因此,只要我在渲染时删除changeSets={data},它就会失败

ReactDOM.render(<App headings = {headings}/>, document.getElementById("container"))

您正在尝试使用道具changeSets时,它实际上是App的状态的一部分。

:

<RecentChangesTable.Rows changeSets={this.props.changeSets} />

应:

<RecentChangesTable.Rows changeSets={this.state.changeSets} />

http://jsbin.com/tuqeciyere/1/edit?js、控制台、输出