0

React-Rails gem を使用しておりitems、Rails コントローラーから json オブジェクトにアクセスしています。

レールコントローラー:

class ItemsController < ApplicationController
  def index
    @items = Item.all
    render json: @items
  end
end

私の ReactAppコンポーネントはこれらの項目にアクセスし、子コンポーネントに prop として渡そうとします:

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>;
4

2 に答える 2