如何在 React 中渲染对象数组的属性? [英] How to render properties of an Array of objects in React?
问题描述
所以,我和我们这里的朋友遇到了完全相同的问题:
一个>Nahush Farkande 的以下(已投票)解决方案:
render() {让用户 = this.props.user ||{};....{用户.email}....}
对我有用...如果 user 是一个对象.但是,在我的特定情况下,我获取并想要呈现的数据是一组对象.
所以,我返回类似的东西:
{user.map((el, idx) => {返回 (<li key = {idx}><div className="panel-body clearfix">{el.title}
)})}
那行不通.我收到一条错误消息,告诉我 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屋!