reactjs - React:在对象内映射数组
问题描述
我正在为应该如此简单的事情而苦苦挣扎。我有一个entry
包含数组的对象:
"timestamp": "Sun Jul 12 2020 23:36:26 GMT-0700 (Pacific Daylight Time)",
"location": "İstanbul, Turkey",
"think": [
"Albanian",
"Slovenian"
],
"dream": "Turkish",
"geolocation": [
41.0082376,
28.9783589
]
}
我想映射到think数组。无论我尝试什么都会返回错误:
TypeError: entry.think is undefined
.
我确信这会起作用,但事实并非如此:
{entry.think.map((think, index) => (
<p key={index}>{think}</p>
))}
编辑:
整个组件:
import React, { useState, useEffect } from "react";
import firebase from "../firebase";
import "../services/localizationService";
const EntrySingle = ({ match }) => {
const { params: { singleId } } = match;
const [entry, setEntry] = useState([]);
useEffect(() => {
firebase
.firestore()
.collection("entries")
.doc('' + singleId)
.get()
.then((doc) => {
const data = doc.data();
setEntry(data);
});
}, [singleId]);
console.log(entry);
return (
<>
<p>dream: {entry.dream}</p>
<p>think: {entry.think}</p>
{entry.think.map((think, index) => {
return <p key={index}>{think}</p>
})}
<p>location: {entry.location}</p>
<p>geolocation: {entry.geolocation}</p>
</>
);
};
export default EntrySingle;
当我返回<p>think: {entry.think}</p>
时,它确实显示了 html 中的内容,如下所示:
think: AlbanianSlovenian
解决方案
以下是可能有效的方法:
const EntrySingle = ({ match }) => {
const {
params: { singleId },
} = match;
const [entry, setEntry] = useState([]);
useEffect(() => {
firebase
.firestore()
.collection("entries")
.doc("" + singleId)
.get()
.then((doc) => {
const data = doc.data();
setEntry(data);
});
}, [singleId]);
console.log(entry);
return (
<>
<p>dream: {entry.dream}</p>
<p>think: {entry.think}</p>
{entry &&
entry.think &&
entry.think.length &&
entry.think.map((think, index) => {
return <p key={index}>{think}</p>;
})}
<p>location: {entry.location}</p>
<p>geolocation: {entry.geolocation}</p>
</>
);
};
entry
基本上,您在从 Firestore 获取之前尝试访问它。
推荐阅读
- .net - ASP.NET MVC - 不能在 Foreach 循环中使用 HTML Raw
- json - 反序列化 JSON swift 4.2
- ios - 我们是否应该使用观察者方法来修改 IBOutlet 属性
- javascript - Javascript类方法绑定不起作用
- javascript - 如何将新文档应用于旧版缩小文件?
- xml - 将 XML 文件保存到 HDFS
- vb.net - 空条件运算符不起作用(显示“调用不是 xxx 的成员”)
- sql - 如果行不符合要求,如何分配值 0
- web - 有关 Microsoft Power BI Embedded 的一般问题
- compilation - 混合编译过程的库路径