【问题标题】:how add Id property on array of objects from the api?如何在 api 的对象数组上添加 Id 属性?
【发布时间】:2022-08-08 20:00:11
【问题描述】:

当我尝试添加一个 Id 属性时,来自 API 的数据没有 id 整个对象都采用相同的 id,如何为数组的每个对象创建一个唯一的 id? 这是我的代码,控制台的屏幕截图显示了所有具有相同 ID 的对象

import \"./styles.css\";
import { useState, useEffect } from \"react\";
import { nanoid } from \"nanoid\";

export default function App() {
  const [tasks, setTasks] = useState([]);

  const getTasks = () => {
    fetch(\"https://opentdb.com/api.php?amount=5&type=multiple\")
      .then((response) => response.json())
      .then((json) => {
        let allTasks = json.results;
        
        const id = nanoid();
       
        allTasks = allTasks.map((currentTask) => {
          return { ...currentTask, isHeld: false, id: id };
        });
        setTasks(allTasks);
      });
  };

  useEffect(() => {
    getTasks();
  }, []);
  useEffect(() => {
    console.log(tasks);
  }, [tasks]);
  return (
    <div className=\"App\">
      {tasks &&
        tasks.map((task) => {
          return <h1> {task.question}</h1>;
        })}
    </div>
  );
}

    标签: javascript reactjs


    【解决方案1】:

    您需要在 map 函数中创建 ID,如下所示:

    import "./styles.css";
    import { useState, useEffect } from "react";
    import { nanoid } from "nanoid";
    
    export default function App() {
      const [tasks, setTasks] = useState([]);
    
      const getTasks = () => {
        fetch("https://opentdb.com/api.php?amount=5&type=multiple")
          .then((response) => response.json())
          .then((json) => {
            let allTasks = json.results;
           
            allTasks = allTasks.map((currentTask) => {
              return { ...currentTask, isHeld: false, id: nanoid() };
            });
            setTasks(allTasks);
          });
      };
    
      useEffect(() => {
        getTasks();
      }, []);
      useEffect(() => {
        console.log(tasks);
      }, [tasks]);
      return (
        <div className="App">
          {tasks &&
            tasks.map((task) => {
              return <h1> {task.question}</h1>;
            })}
        </div>
      );
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 2021-04-26
      • 2021-03-22
      • 2011-11-09
      相关资源
      最近更新 更多