简体   繁体   English

React 组件未在 map 循环内加载

[英]React component does not load inside map loop

I was building a react app and got stuck at this issue where my component does not load in the case of a loop.我正在构建一个反应应用程序并陷入了这个问题,即我的组件在循环的情况下无法加载。 Below is my code for StoriesContainer.js and Story.js.下面是我的 StoriesContainer.js 和 Story.js 代码。 As you will notice I am calling the Story component twice, the first call is outside the loop and that renders perfectly.您会注意到我两次调用 Story 组件,第一次调用在循环之外并且完美呈现。 However, my second call is inside the map loop and that does not seem to work.但是,我的第二个电话是在 map 循环内,这似乎不起作用。 I am confused about what I might be doing wrong since I tried to look it up online and this was the correct way to do it.我很困惑我可能做错了什么,因为我试图在网上查找它,这是正确的方法。

If anyone can help that would be great.如果有人可以提供帮助,那就太好了。 The image the result I get right now.我现在得到的结果图像。

import React, { useState, useEffect } from "react";
import { getStoryID } from "../services/api";
import { Story } from "./Story";

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

  useEffect(() => {
    getStoryID().then((data) => {
      console.log(data);
      setData(data);
    });
  }, []);

  return (
    <>
      <Story id={95666} />
      <h1>App.js</h1>
      <ul>
        {data.map((id) => {
          // eslint-disable-next-line no-lone-blocks
          {
            console.log(id);
          }
          <Story key={id} id={id} />;
        })}
      </ul>
    </>
  );
};
export const Story = ({ id }) => {
  
  return <h1>This is story {id}</h1>;
};

在此处输入图像描述

You're not returning from your map callback.您不会从 map 回调中返回。

  <ul>
    {data.map((id) => {
      // eslint-disable-next-line no-lone-blocks
      {
        console.log(id);
      }
      return <Story key={id} id={id} />;
    })}
  </ul>

or simply或者干脆

  <ul>
    {data.map((id) => <Story key={id} id={id} />}
  </ul>

Both will be fine and I will prefer the second one.两者都可以,我更喜欢第二个。

use the return keyword before <Story> in the map.在 map 中的<Story>之前使用return关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM