首页 > 解决方案 > 如何映射从 mongoDB 获取的字符串数组并在每个帖子中显示一个特定的标题/正文

问题描述

我有一个使用 React 和 Express Node 构建的 RESTful 应用程序,它是一个简单的表单,主体和标题输入覆盖在背景图像上,当用户单击保存时,他们会被定向到另一个组件,其中 axios.get 请求显示他们的帖子。

我的目标是检索保存的数据并在数组中显示图像/帖子。现在我只是在测试帖子检索,稍后我会处理图像。在 Postman 中测试路由时,我可以使用 来查看我的所有帖子http://localhost:5000/getall,但是当我在我的 axios.get 请求中使用此路径时,我看到所有帖子杂乱无章,没有分开:请参见下图中的示例。要访问我<Card /> I import the a Card component (在 SharewallComp.js 文件中使用 `) 的数组。

如何映射取自 mongo dB 的这个字符串数组并在每个帖子中只显示一个标题/正文?

我尝试了以下方法:

  1. 按 id 检索数据:let res = await axios.get(http://localhost:5000/getall${match.params.id});但我得到TypeError: Cannot read property 'params' of undefined.

  2. 我还尝试了以下没有匹配参数的方法,我的结果只是数字,请参见下面的错误截图:

      <Card.Title className="text-center mt-5">
         Title: {(title).map((t, index) => (
         <Card.Text key={index} className="text-light"> {(t, index)} </Card.Text>
         ))}
          Body: {(body).map((b, index) => (
         <Card.Text key={index} className="text-light"> {(b, index)} </Card.Text>
         ))}
    

这是我的尝试:映射不是我最强的技能。我非常感谢任何帮助!

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

import Cards from "./Cards";

const ShareWallComp = ({ match }) => {
  const [url, setUrl] = useState([]);
  const history = useHistory();

    const loadimg = async () => {
      try {
        let res = await axios.get(
          `http://localhost:5000/geturls/${(match.params.name="grace")}`
        );
        setUrl(res.data.map((d) => d.url));
      } catch (error) {
        console.log(error);
      }
    };

  useEffect(() => {
  // login code
    loadimg();
  }, []);

  return (
    <div className="getcross">
      <Container className="mt-5 ml-auto mr-auto">
        <div className="mt-4">
          <Navi />
        </div>
        <h1 className="text-center">
          ShareVerse
          <span className="text-success"> Wall</span>
        </h1>
        <div>
          <div className="shadow p-3 mb-5 bg-white rounded">
            <Card className="bg-dark shadow text-white">
              {url
                .filter((name) => name.includes("grace"))
                .map((urlData) => (
                  <Card.Img key={url.name} src={urlData} alt="Card image" />
                ))}
              <Card.ImgOverlay>
                <div className="text-center"><Cards /></div>
              </Card.ImgOverlay>
            </Card>
          </div>
        </div>
      </Container>
    </div>
  );
};

export default ShareWallComp;

这是我有输入数组的组件

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

const ComponentName = (props) => {   

  const [body, setBody] = useState([]);
  const [title, setTitle] = useState([]);

  const loadData = async () => {
    try {
      //   let res = await axios.get(
      let res = await axios.get(`http://localhost:5000/getall`);

      setTitle(res.data.map((t) => t.title));
      setBody(res.data.map((b) => b.body));
    } catch (error) {
      console.log(error);
    }
  };

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

    return (
      <div className="compoentclass">
        <Container className="mt-5 ml-auto mr-auto">
          <div className="text-center">
            <Card.Title className="text-center mt-5">
            Title: {(title).map((t) => (
            <Card.Text className="text-light"> {(t)} </Card.Text>
            ))}
             Body: {(body).map((b) => (
            <Card.Text className="text-light"> {(b)} </Card.Text>
            ))}
            </Card.Title>
          </div>
         </Container>
      </div>
        );
    }      

export default ComponentName;

帖子聚集的例子 在此处输入图像描述

使用 id 检索数据时出错 在此处输入图像描述

下面的屏幕截图是我希望我的代码执行的示例: [1]:https://i.stack.imgur.com/yeNgZ.jpg

标签: node.jsarraysreactjsfor-loop

解决方案


答案是获取所有数据而不是映射它:请参阅下面更正的代码,我希望这对那里的一些人有所帮助!因此,而不是setTitle(res.data.map((t) => t.title));and setBody(res.data.map((t) => t.Body));,只需获取所有数据:setPosts(res.data);然后调用{post.body}

import React, { useState, useEffect } from "react";
import Container from "react-bootstrap/Container";
import Card from "react-bootstrap/Card";
import Button from "react-bootstrap/Button";
import axios from "axios";
import "./css/sharewall.css";

const ComponentName = () => {
  const [posts, setPosts] = useState([]);
  const [comment, setComment] = useState("");
  const [id, setId] = useState("");

  const loadData = async () => {
    try {
      let res = await axios.get(`http://localhost:5000/getall`);
      setPosts(res.data);
    } catch (error) {
      console.log(error);
    }
  };

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

  return (
    <div className="compoentclass">
      <Container className="mt-5 ml-auto mr-auto">
        <div className="text-center">
          {posts.map((post, index) => (
            <div>
              <Card className="">
                <Card.Img alt="" src={post.url} />
                <Card.ImgOverlay className="overlay">
                  <Card.Title className="text-center mt-5">
                    <Card.Text className="cardStyle text-light">
                      {post.body}
                    </Card.Text>
                  </Card.Title>
                </Card.ImgOverlay>
              </Card>
              {posts.map((post, index) => (
              ))}
              </div>
            </div>
          ))}
        </div>
      </Container>
    </div>
  );
};

export default ComponentName;

推荐阅读