我有以下组件,它与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>
);
}
});
但是当我把它放在那里时,我收到错误: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) %>
答案 0 :(得分:2)
使用Array
(data.items
)代替Object
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>;
}
答案 1 :(得分:0)
除了Alexander所说的,你不必将状态值赋给变量。您可以直接在div标签内部进行操作
<div> { this.state.data.items } <div>
并使用.map获取值。
{this.state.data.items.map(objval =>
<div>
{objval.name}
</div>
)}
希望有所帮助:)