【问题标题】:How could I display in my front a back request?我怎么能在我的前面显示一个后面的请求?
【发布时间】:2020-10-02 12:07:37
【问题描述】:

我已经创建了我的后端并且它可以工作。我测试了不同的 Axios 请求以创建表单。 在我的 React 前端项目中,我创建了一个 POST axios 请求,我在 console.log(response.data) 中获得了一个带有 id、标题和问题的对象。

我被卡住了,因为我不知道如何在我的前面显示对象的数据。

这是我前面的 React 代码:

import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import axios from "axios";

const NewForm = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      if (data.length === 0) {
        const response = await axios.post(
          "https://back-formnest-lereacteur.herokuapp.com/form/create",
          {
            title: "Your event",
          }
        );
        console.log(response.data);
        setData(response.data);
      }
    };

    fetchData();
  }, [data]);

  return (
I am completely stuck here to display the data of my backend in my front 

这是我的后端代码:

const express = require("express");

const router = express.Router();

const Form = require("../models/Form");


router.post("/form/create", async (req, res) => {
  try {

    if (req.fields.title) {
      const newForm = new Form({
        title: req.fields.title,

      });


      await newForm.save();
      return res.json(newForm);
    } else {
      return res.status(400).json({ error: "Missing parameters" });
    }
  } catch (e) {
    return res.status(400).json({ error: e.message });
  }

});

这是我的 console.log(response.data) 我想显示在我的 React 前端页面中:

我编辑了我的代码,但出现错误:

import React, { useState, useEffect } from "react";
/* import { Link } from "react-router-dom"; */
import axios from "axios";

const NewForm = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      if (data.length === 0) {
        const response = await axios.post(
          "https://back.herokuapp.com/form/create",
          {
            title: "Nouveau formulaire",
          }
        );
        console.log(response.data);
        setData(response.data);
      }
    };

    fetchData();
  }, [data]);

  return (
    <>
      <div>My forms</div>

      <div>
        {data && (
          <>
            <p>{data.title}</p>
            {data.questions.map((question, index) => (
              <div> {question} </div>
            ))}
          </>
        )}
      </div>
    </>
  );
};

export default NewForm;

大家好,

我更新了我的代码,但仍然有错误代码(TypeError:无法读取未定义的属性“长度”)

   <>
      <div>My forms</div>

      <div>
        {data && (
          <>
            <p>{data.title}</p>
            {data.questions.length &
              data.questions.map((question, index) => {
                return <p key={index}>{question}</p>;
              })}
          </>
        )}
      </div>
    </>

我再次更新了我的代码,我只成功地显示了我的表单的标题,但我没有成功地显示我的问题数组中包含的数据。我有一个“0”而不是我的数据。请帮忙

return (
    <>
      <div>My forms </div>

      <div>
        {data && data.questions && (
          <>
            <div>{data.title} </div>

            {data.questions.length &
              data.questions.map((question, index) => {
                return <p key={index}>{question}</p>;
              })}
          </>
        )}
      </div>


    </>

我又更新了,出现同样的错误:

return (
    <>
      <div>My forms </div>

      <div>
        {data &&
          data.questions &&
          data.questions.length(
            <>
              <div>{data.title} </div>

              {data.questions.map((question, index) => {
                return <p key={index}>{question}</p>;
              })}
            </>
          )}
      </div>

【问题讨论】:

    标签: reactjs mongoose frontend backend


    【解决方案1】:

    看起来您的后端响应了一个对象,所以您可以这样做。

    1) 像这样将您的初始状态更改为未定义。

    const [data, setData] = useState([]);
    

    到

    const [data, setData] = useState(undefined);
    

    那你就可以像这样在显示中使用了

    return (
        <div>
            {data && (
                <>
                    <p>{data._id}</p>
                    <p>{data.title}</p>
                    {data.question.length && data.question.map((question,idx) => {
                        // this is assuming that each question is just a string and not an object
                     return   (<p key={idx}>{question}</p>)
                    })}
                </>
            )}
        </div>
    )
    

    【讨论】:

    • 感谢 Shmili 的回答,我试过了,但控制台中有 2 个错误。我想显示所有带有标题的对象,请包含问题和答案。我在问题的编辑版本中分享了错误的屏幕截图(最后一张图片)
    • Yoni,我更新了答案,希望它现在可以工作,我将这一行 &lt;p key={idx}&gt;{question}&lt;/p&gt; 更改为 return (&lt;p key={idx}&gt;{question}&lt;/p&gt;)
    • 感谢 Shmili 的更新。我发布了更新的代码,但仍然出现错误:typeError: Cannot read property 'length' of undefined
    • 你把const [data, setData] = useState([]);改成const [data, setData] = useState(undefined);了吗?
    • 另外,您可能还想在映射问题之前进行检查,将 {data.questions.length &amp;&amp; data.questions.map((question,idx) =&gt; { 更改为 {data.questions &amp;&amp; data.questions.length &amp;&amp; data.questions.map((question,idx) =&gt; {
    【解决方案2】:

    你已经完成了最困难的部分!

    如果您想将它们显示出来,现在只需将.map 放在问题数组上?

    <div>
     {data.questions.map((question => (
        <div> {question.title} </div>
     ))}
    </div>
    

    我只是做了一个简单的例子,但当然你可以显示尽可能多或尽可能少

    当然,您可以渲染任何处于状态的东西。因此,如果您想显示标题,请执行以下操作:

    {data.title} 随心所欲

    【讨论】:

    • 感谢您的反馈和帮助。我成功地显示了我的表单的标题,但我想显示所有对象而不仅仅是问题。请问我该怎么办?
    • 通过data.显示它们,然后是属性的名称。如果它是一个数组,你需要使用我显示 data.id 的 map 函数,以同样的方式显示 id
    • 谢谢你,但是当我映射问题数组 TypeError: Cannot read property 'map' of undefined
    • 发布您到目前为止所拥有的内容,我们将完成它。未定义的地图意味着您要映射的东西是未定义的
    • @Yoni 改成 data &amp;&amp; data.questions.length (
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 2019-04-06
    • 2021-03-06
    • 2016-09-21
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    相关资源
    最近更新 更多