【问题标题】:How can I map string array taken from mongoDB and show one specific title/body per post如何映射从 mongoDB 获取的字符串数组并在每个帖子中显示一个特定的标题/正文
【发布时间】:2021-06-07 18:17:03
【问题描述】:

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

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

如何映射从 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 的数据时出错

下面的屏幕截图是我希望我的代码执行的示例:

【问题讨论】:

  • 关于key的错误信息不是错误,是警告,您可以通过providing a unique key修复它。
  • 你如何渲染ShareWallComp?似乎您没有将 match 道具传递给它。您是否将其渲染为 React Router 路径?
  • @codemonkey 这是一个路由器路径,我从一个组件中检索到数据,该组件的 id 捕获了帖子并将其传递到 url。我复制了从 mongo 呈现保存数据的组件。

标签: node.js arrays reactjs for-loop


【解决方案1】:

答案是获取所有数据而不是对其进行映射:请参阅下面更正的代码,我希望这对那里的一些人有所帮助!所以不用setTitle(res.data.map((t) =&gt; t.title));setBody(res.data.map((t) =&gt; 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多