我有以下组件,它很像 React.js 主教程。基本上,我有一个 api,我从中提取并尝试加载数据:
var Box = React.createClass({
getInitialState: function () {
return {
data: {
items: []
}
};
},
loadStuffFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
componentDidMount: function() {
this.loadStuffFromServer();
},
render: function() {
var blah = this.state.data;
return (
<div>
{ blah }
</div>
);
}
});
但是,当我在那里放置 blah 时,我收到错误:Uncaught Error: Invariant Violation: Objects are not valid as a React child (found: object with keys {items}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of
盒子.
我用 React Rails 和 <%= react_component('Box',url: "URLHERE", pollInterval: 1000) %>
调用我的组件
最佳答案
使用数组
(data.items
)而不是对象
var blah = this.state.data.items;
__________________________^^^^^^___
render: function () {
var blah = this.state.data.items.map(function (item) {
return <p>
{ item.content }
</p>;
});
return <div>
{ blah }
</div>;
}
关于javascript - 对象无效问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34464280/