私はReact-Railsの宝石を使用していて、Railsのコントローラーからjsonオブジェクトitems
にアクセスしています。react jsonオブジェクトはReactの子としては無効です
Railsのコントローラ:
class ItemsController < ApplicationController
def index
@items = Item.all
render json: @items
end
end
私はApp
コンポーネントは、これらの項目にアクセスして、子コンポーネントに小道具としてそれを渡そうとリアクト:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
items: {},
activeTab: 'items'
};
}
componentDidMount() {
$.getJSON('/items.json', (response) => {
this.setState({ items: response })
});
}
render() {
return (
<div>
<ItemsContent items={this.state.items}>
</div>
);
}
}
そして、この子コンポーネントは次のようになります。
class ItemsContent extends React.Component {
render() {
return (
<div>
<div>Items: {this.props.items}</div>
</div>
);
}
}
ItemsContent.propTypes = {
items: React.PropTypes.object
};
このエラーが発生します:
react.js?body=1:1324 Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {}). 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 `ItemsContent`.
この問題を回避するにはどうすればよいですか? ReactコンポーネントでJSONオブジェクトを簡単に使用する方法はありますか?
は、今私は、配列内のJSONオブジェクトをラップしようとした:
tabbedContent = <ItemsContent items={[this.state.items]}></ItemsContent>;
で
App.js
あなたはthis.props.items内のすべての項目を表示しようとしていますか? – erichardson30
はい、すべてのアイテムを表示しようとしています。 – user2082000