我正在学习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"))
答案 0 :(得分:1)
当它实际上是changeSets
状态的一部分时,你试图使用道具App
。
此:
<RecentChangesTable.Rows changeSets={this.props.changeSets} />
应该是:
<RecentChangesTable.Rows changeSets={this.state.changeSets} />