React js:无法将数组中的第一个对象作为道具发送

React js: Can´t send first object in array as prop

我正在尝试构建一个小型 React.js 应用程序,我的组件结构如下所示:

MainComponent
    - CategoryList
        -Category
    - ItemsList 
        -Item

我的 MainContent 组件对 componentDidRender: 中的状态数据执行 ajax 请求,其中 returns 这个对象:

data:[
Object[0]
 -name
 -items[]
,
Object[1],
Object[2]
]

现在,我希望我的 CategoryList 按名称写出所有类别,这工作得很好,但我还想打印出所选类别的项目。这是我的 ItemsList 组件:

 var ItemsList = React.createClass({
    render:function(){

         var itemNodes = this.props.category.items.map(function(item){
            return (
                <Item name={item.name} />
            );
        });

        return(
            <div className="itemList">
            {itemNodes}
            </div>
        );
    }
});

这就是我从父组件传递 "category"-属性 的方式

<ItemsList category={this.state.data[0]} />

我收到一条错误消息说 "Can´t read property items of undefined",这意味着从未分配过 category 属性。我知道 this.state.data 包含一个对象数组,所以我看不到这里的错误。

我做错了什么?

编辑:根据要求,这是我的 MainComponent:

var MainComponent = React.createClass({
    getInitialState:function(){
        return {data: []};
    },
    componentDidMount:function(){
        $.ajax({
            type:'get',
            url: '/categories',
            dataType: 'json',
            success:function(data){
                this.setState({data: data});
            }.bind(this)

        });
    },
    render: function(){
        return (
        <div className="row">
            <div className="col-md-6">
                <CategoryList categories={this.state.data} />
            </div>
            <div className="col-md-6">
            <ItemsList category={this.state.data[0]} />
            </div>
        </div>

        );
    }
});

您的主要组件在 data 中使用空数组初始化状态。渲染总是会失败,因为没有 this.state.data[0].

有人可能会回答说 ajax 请求将为此状态 属性 data 提供值(假设您的 Web 服务提供了一个有效的数组)。 但是,这只会发生在从服务器收到响应之后,第一次渲染后不会发生。

如果信息立即可用,可以 setState 方法 componentWillMount 或组件构造函数,以避免触发第二次渲染:

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state synchronously in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.

在这种情况下,由于我们是在等待远程信息,因此React文档仍然推荐使用componentDidMount,这里同样采用:

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.

因此,组件的渲染方法必须能够处理缺失的状态变量。有多种方法可以解决这个问题,但是在我们拥有 data 之前阻止嵌套元素被渲染是最简单的方法。通过一些额外的逻辑,应用程序可以通知用户特定组件正在加载。

render() {
    return (
    <div className="row">
        <div className="col-md-6">
            <CategoryList categories={this.state.data} />
        </div>
        <div className="col-md-6">
          {this.state.data.length > 0 &&
            <ItemsList category={this.state.data[0]} />
          }
        </div>
    </div>
    );
}