如何在 React 中渲染对象数组的属性? [英] How to render properties of an Array of objects in React?

查看:26

)})}

那行不通.我收到一条错误消息,告诉我 user.map 不是函数(在 [HMR] 连接之前).

我预计一旦 API 获取用户对象数组,组件将重新渲染,然后组件将显示用户数组每个对象的标题列表(在 [HMR] 连接后).

如果你的 user(我建议重命名为 users)是一个数组,那么你不能使用{} 作为默认值.您应该使用 [] 作为默认值:

const user = this.props.user ||[]

或者,您可以使用完全不同的分支来处理加载情况:

if (!this.props.user) {返回 (<div>... 我正在加载的占位符 ... </div>);}

So, I have the exact same problem as our friend here :

How to render properties of objects in React?

The below (upvoted) solution by Nahush Farkande :

 render() {
     let user = this.props.user || {};
     ....
         {user.email}
     ....
 }

works for me... if user is an object. However, in my specific case, the data I fetch and want to render is an array of objects.

So, I return something like that :

                <ul>                                    
                    {
                        user.map( (el, idx) => {
                            return (
                                <li key = {idx}>
                                    <div className="panel-body clearfix">
                                        {el.title}
                                    </div>
                                </li>               
                            )
                        })
                    }
                </ul>

That doesn't work. I get an error message that tells me that user.map is not a function (before [HMR] connected).

I expected that once the API fetches the user array of objects, the component would re-render and then the component would show the list of titles from each object of the user array (after [HMR] connected).

解决方案

If your user (I recommend to rename to users) is an array, then you cannot use {} as the default. You should use [] as the default value:

const user = this.props.user || []

or, you can use a completely different branch to handle the loading case:

if (!this.props.user) {
    return (
       <div> ... my loading placeholder ... </div>
    );
}

这篇关于如何在 React 中渲染对象数组的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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