【问题标题】:React: Mapping array inside objectReact:在对象内映射数组
【发布时间】:2020-07-14 18:44:36
【问题描述】:

我正在努力解决应该如此简单的事情。我有一个名为 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;

当我返回&lt;p&gt;think: {entry.think}&lt;/p&gt; 时,它 像这样在 html 中显示内容:

think: AlbanianSlovenian

【问题讨论】:

  • 错误是什么?也可以提供一个完整的例子吗?也许您在哪里执行该代码?
  • 你需要说出错误信息的内容。
  • TypeError: entry.think is undefined
  • 抱歉,如果没有minimal reproducible example,就无法猜出问题所在。如果您有一个名为entry 的变量,并且它是一个在键think 中有一个数组的对象,那么entry.think 不能抛出错误,所以问题出在其他地方。显示整个组件将是一个好的开始。
  • 基于您提供的稀缺信息,我只能假设 - 您是否正在从 API 获取此对象,并且在它完成获取之前调用了 map()

标签: reactjs


【解决方案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 之前尝试访问它。

【讨论】:

  • 它仍然没有返回任何内容。我之前尝试过类似的东西,但没有显示。
  • 它是否只为think 返回未定义?还有什么是singleIduseEffect 什么时候起火?
  • Firebase 返回一个对象。 entry.length 永远不会是真的。
  • 最后一次编辑有效!添加entry.think.length 是缺失的部分。谢谢!
猜你喜欢
  • 2020-05-15
  • 1970-01-01
  • 1970-01-01
  • 2021-01-30
  • 1970-01-01
  • 2017-04-22
  • 1970-01-01
  • 2017-06-01
  • 2021-06-23
相关资源
最近更新 更多