Реагировать json Объекты недопустимы как дочерние элементы React
Я использую гем React-Rails и доступ к объекту json items
с контроллера Rails.
Контроллер 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`.
Как мне обойти это? Есть ли способ легко использовать объекты JSON в моих компонентах React?
Прямо сейчас я попытался обернуть объект JSON в массив:
tabbedContent = <ItemsContent items={[this.state.items]}></ItemsContent>;
2 ответа
Вы можете перебрать список в render()
из App
Составная часть. И создайте элемент React.Component для каждого из элементов.
App.js
render () {
return (
<div>
this.state.items.map( function(item){
<Item value={item} key={}>
});
</div>
);
}
В Item.js
class Item extends React.Component {
render () {
return (
<div>
return <div> Item : {this.props.value} </div>
</div>
);
}
}
Item.propTypes = {
value: React.PropTypes.object
};
Поскольку this.state.items является массивом, вы не можете выгружать все элементы в массиве таким образом. Вы можете использовать API массива javascript, перебирать элементы и отображать их следующим образом:
class ItemsContent extends React.Component {
render () {
return (
<div>
{
this.props.items.map(function(item) {
return <div> Item : {item} </div>
}
</div>
);
}
}
ItemsContent.propTypes = {
items: React.PropTypes.object
};
Если вы получаете только один объект каждый раз, тогда карта не будет работать, и вам нужно разбить объект по свойству, чтобы отобразить все:
render () {
return (
<div>
<div> Item : {this.props.items.a} , {this.props.items.b}, {this.props.items.c} </div>
</div>
);
}