开发者问题收集

React 抛出错误:无法读取未定义的属性“map”

2016-08-24
690

我正在学习 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/[email protected]/dist/react.min.js:13:17508)
    at _renderValidatedComponent (https://npmcdn.com/[email protected]/dist/react.min.js:13:17644)
    at performInitialMount (https://npmcdn.com/[email protected]/dist/react.min.js:13:13421)
    at mountComponent (https://npmcdn.com/[email protected]/dist/react.min.js:13:12467)
    at Object.mountComponent (https://npmcdn.com/[email protected]/dist/react.min.js:15:2892)
    at h.mountChildren (https://npmcdn.com/[email protected]/dist/react.min.js:14:26368)
    at h._createInitialChildren (https://npmcdn.com/[email protected]/dist/react.min.js:13:26619)
    at h.mountComponent (https://npmcdn.com/[email protected]/dist/react.min.js:13:24771)
    at Object.mountComponent (https://npmcdn.com/[email protected]/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"))
1个回答

您试图使用 props changeSets ,而它实际上是 App s 状态的一部分。

这:

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

应该是:

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

http://jsbin.com/tuqeciyere/1/edit?js,console,output

adam-beck
2016-08-24