【问题标题】:Display (map) list of messages nested in an object (MERN)显示(映射)嵌套在对象中的消息列表 (MERN)
【发布时间】:2021-12-31 10:42:46
【问题描述】:

我正在学习 MERN,并希望在 React UI 中显示来自 Mongo 数据库的消息列表。

我在 Mongo 中的 UserSchema:

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  phone: {
    type: Number,
    required: true,
  },
  
  messages: [
    {
      name: {
        type: String,
        required: true,
      },
      email: {
        type: String,
        required: true,
      },
      phone: {
        type: Number,
        required: true,
      },
      message: {
        type: String,
        required: true,
      },
    },
  ],
  tokens: [
    {
      token: {
        type: String,
        required: true,
      },
    },
  ],
});

React 中 Home.js 中的代码:

import React, { useState, useEffect } from "react";

const Home = () => {
  const [userName, setUserName] = useState({});
  const [show, setShow] = useState(false);

  const userHome = async () => {
    try {
      const res = await fetch("/userdata", {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      });

      const data = await res.json(); //successfully getting complete json data in console.

      console.log(data);
      setUserName(data);
      setShow(true);
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    userHome();
  }, []);

  return (
    <>
      <div className="page-wrap d-flex flex-row align-items-center">
        <div className="container">
          <div className="row justify-content-center">
            <div className="col-md-12 text-center">
              <span className="display-1 d-block">
                <p> Welcome {show ? "Back!" : ""} </p>
                <h1>{userName.name}</h1>
                <h2>
                  {show
                    ? "What you want to do today?"
                    : "Your own Portal.."}
                </h2>
              </span>
              <div className="mb-4 lead">
                {show
                  ? ""
                  : "You need to register and login for accessing your profile."}
              </div>
              <div>
                <div>Messages:{userName[0].message}</div> 
            {/* wants to display list of all message here */}

              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default Home;

我尝试获取所有消息列表的方法

我尝试了 map 方法但没有成功,并且尝试了下面的代码仍然没有成功。好心提醒。我想在加载时显示所有消息 Message 1、Messag 2 等。

<div>Messages:{userName[0].message}</div>

浏览器中的错误消息:

TypeError: Cannot read properties of undefined (reading 'message')

我解决了如下

已删除

<div>Messages:{userName[0].message}</div> 
        {/* wants to display list of all message here */}
          </div>

添加:

 <div>
   {userName.messages?.map((msg1) => (
     <li key={msg1._id}>{msg1.message}</li> ))}
 </div>

【问题讨论】:

  • 消息位于messages 属性中,因此要访问第一条消息的文本,您需要使用userName.messages[0].message 如果您不理解这一点(这很简单),也许您应该首先学习javascript的基础知识。

标签: node.js reactjs express mongoose


【解决方案1】:

你可以删除这部分吗:

              <div>
                <div>Messages:{userName[0].message}</div> 
            {/* wants to display list of all message here */}

              </div>

改为添加:

  <div>{
    data.map(result => (
      <div key={result._id}>
          <h2>{result.name}</h2>
          <p>Some text: {result.messages}</p>
      </div>
    ))
  }</div>

如果上面的代码有效,那么您可以调整它以显示您想要的消息,我认为是这样的:

<p>Some text: {result.messages[0].message}</p>

如果有效,请告诉我。

【讨论】:

  • 感谢好友的帮助!我已经找到了解决方案,并在我的查询部分进行了更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-26
  • 1970-01-01
  • 2020-09-27
  • 2013-08-01
  • 2019-04-26
  • 1970-01-01
  • 2022-07-22
相关资源
最近更新 更多