反应:在对象内部映射数组

时间:2020-07-14 18:44:36

标签: reactjs

我正在努力使应该如此简单。我有一个名为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
  ]
}

,我想映射到思考数组。无论我尝试什么都会返回错误: 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

1 个答案:

答案 0 :(得分:-1)

这可能是可行的:

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

基本上,您是在尝试从Firestore提取entry之前对其进行访问。