【问题标题】:Uncaught TypeError: workouts.map is not a function "react"未捕获的类型错误:锻炼.map 不是函数“反应”
【发布时间】:2022-08-11 05:07:09
【问题描述】:

这是来自服务器的 JSON 文件

 {workouts: Array(3)}
workouts: Array(3)
0: {_id: \'idnumber1\', title: \'pullup\', reps: 40, load: \'20\', createdAt: \'2022-07-20T18:06:39.642Z\', …}
1: {_id: \'idnumber2\', title: \'situp\', reps: 40, load: \'20\', createdAt: \'2022-07-20T10:10:14.078Z\', …}
2: {_id: \'idnumber3\', title: \'pushup\', reps: 10, load: \'0\', createdAt: \'2022-07-19T14:33:58.678Z\', …}
length: 3
[[Prototype]]: Array(0)
[[Prototype]]: Object

//这是我在反应中所做的代码

import { useEffect, useState } from \"react\";

const Home = () => {
  const [workouts, setworkouts] = useState(null);

  useEffect(() => {
    const fecthworkout = async () => {
      const response = await fetch(\"/api/workout\");
      const json = await response.json();

      if (response.ok) {
        setworkouts(json);
      }
    };

    fecthworkout();
  }, []);

  useEffect(() => {
    console.log(\"hello\");
  }, []);

  return (
    <div className=\"home\">
      <div className=\"workouts\">
 
        {workouts &&
          workouts.map((workouts) => (
           <p key={workouts._id}>{workouts.title}</p>
          ))}
      </div>
    </div>
  );
};

export default Home;

//谁能告诉我如何停止错误?

我被困在这里我需要帮助

我被困在这里我需要帮助

  • 似乎锻炼不是一个数组(它没有 .map 方法)我猜它是一个具有“锻炼”属性的对象。改变这个: setworkouts(json); -> setworkouts(json.workouts);
  • 使用workouts.workouts.map()

标签: javascript reactjs express


【解决方案1】:

你的useState 钩子默认应该是useState([]) 而不是useState(null)

【讨论】:

    【解决方案2】:

    我遇到了同样的问题。我相信在进入 json 中的锻炼数组之前,可能还有另一层嵌套。无论如何,这对我有用 setWorkouts(json.workouts)

    【讨论】:

      猜你喜欢
      • 2022-11-19
      • 1970-01-01
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      • 2017-07-12
      相关资源
      最近更新 更多