【问题标题】:ReactJS print nested JSON inside a function using map((item, index))ReactJS 使用 map((item, index)) 在函数内打印嵌套的 JSON
【发布时间】:2022-11-12 14:38:42
【问题描述】:

我正在开发看板。我使用 ReactJS 为每个阶段中打开的阶段和任务调用后端。这是我从后端获得的一个非常简单的 JSON。

JSON

[
  {
    "open_tasks": [
      {
        "task_id": 37,
        "task_title": "Develop frontend"
      },
      {
        "task_id": 38,
        "task_title": "Create app"
      }
    ],
    "stage_id": 6,
    "stage_title": "Tasks"
  },
  {
    "open_tasks": [],
    "stage_id": 15,
    "stage_title": "Blocked"
  },
  {
    "open_tasks": [],
    "stage_id": 18,
    "stage_title": "Finished"
  }
]

现在我想使用 ReactJS 打印嵌套的 JSON,但是我不能在地图中使用地图。

import { useEffect, useState } from "react";

export function IndexKanbanBoard() {
  const [stagesWithOpenTasks, setStagesWithOpenTasks] = useState(() => []);

  // Load stages
  const loadStagesWithOpenTasksForBoard = async (e) => {
    let result = await fetch("https://localhost:5002/api/kanban_boards/get_stages_with_open_tasks_for_board", {
      method: "GET",
      headers: {
        'Authorization': 'Bearer ' + 'bla bla'
      }
    });
    let resultJson = await result.json();
    if (result.status === 200) {
      setStagesWithOpenTasks(resultJson.map(fetch_object => {
        return fetch_object
      }))
    }
  };

  // On load
  useEffect(() => {
    loadStagesWithOpenTasksForBoard()
  }, []);

  return (
    <div>
      {stagesWithOpenTasks.map((item, index) => (
        <div key={index}>
          <h2>{item.stage_title}</h2>

          <p>I WANT TO SHOW open_tasks HERE</p>
        </div>
      ))}
    </div>
    );
}
  
export default IndexKanbanBoard;

如何在 React JS 中循环嵌套 JSON?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    将下一个数组项分配给变量将有所帮助,请看一下

      return (
        <div>
          {data.map((item, index) => {
            const openTasks = item["open_tasks"];
            return (
              <div key={index}>
                <h2>{item.stage_title}</h2>
                {openTasks.map((item) => (
                  <p>{item.task_title}</p>
                ))}
                <p></p>
              </div>
            );
          })}
        </div>
      );
    

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 1970-01-01
      • 2021-10-17
      • 2016-03-15
      • 2020-11-15
      • 2017-05-26
      • 1970-01-01
      • 2015-06-21
      • 1970-01-01
      相关资源
      最近更新 更多