首页 > 解决方案 > 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

标签: reactjs

解决方案


以下是可能有效的方法:

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 获取之前尝试访问它。


推荐阅读