React js:不能将数组中的第一个对象作为prop发送 [英] React js: Can´t send first object in array as prop

查看:107
本文介绍了React js:不能将数组中的第一个对象作为prop发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im trying to build an small React.js application and my component structure looks like this:

MainComponent
    - CategoryList
        -Category
    - ItemsList 
        -Item

My MainContent组件对 componentDidRender中的状态数据执行ajax请求:返回此对象:

My MainContent component does an ajax request for its state data in the componentDidRender: which returns this object:

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

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

Now, I want my CategoryList to write out all the Categories by name, which works just fine, but I also want to print out the items of the selected category. This is my ItemsList component:

 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属性的方法

And this is how I pass on the "category"-property from my the parent component

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

我收到错误说无法读取未定义的属性项意味着类别道具从不被分配了。我知道this.state.data包含一个对象数组,所以我在这里看不到错误。

I get an error say "Can´t read property items of undefined" meaning that the category prop never was assigned. I know that this.state.data contains an array of objects so I don´t see the error here.

我做错了什么?

编辑:每个请求,这是我的MainComponent:

Per request, this is my 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>

        );
    }
});


推荐答案

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

Your main component initializes the state with an empty array in data. A render would always fail because there is no this.state.data[0].

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

One would probably reply that the ajax request will provide the value for this state property data (supposing that your web service is providing a valid array). However, this only happens after the response was received from the server, which will not happen after the first render.

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

If the information was available immediately, one could either setState on the method componentWillMount or the component constructor, so as to avoid triggering a second render:


在安装发生之前立即调用componentWillMount()。它在$(b)之前调用
,因此在
中同步设置状态此方法不会触发重新渲染。避免在此方法中引入任何
副作用或订阅。

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 ,以及在这里使用:

In this case, since we are waiting for remote information, the React documentation still recommends the use of componentDidMount, as well employed here:


在组件安装
后立即调用componentDidMount() 。需要DOM节点的初始化应该放在这里。如果
需要从远程端点加载数据,这是
实例化网络请求的好地方。在这个方法中设置状态将
触发重新渲染。

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.

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

Therefore, the component's render method must be able to handle the missing state variable. There are multiple ways to approach this, but preventing the nested element from being rendered until we have data is the easiest approach. With some additional logic, the application could inform the user that the particular component is loading.

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>
    );
}

这篇关于React js:不能将数组中的第一个对象作为prop发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆