NodeJS 为什么从后端获取的数据显示在控制台中,而不是在网页上?

0ejtzxu1  于 2023-01-01  发布在  Node.js
关注(0)|答案(3)|浏览(208)

这里我通过API从后端获取了训练。它在控制台中显示输出,但无法在网页中Map训练状态。

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

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

  useEffect(() => {
    const fetchWorkouts = async () => {
      const response = await fetch("http://localhost:4000/api/workouts");
      const json = await response.json();

      if (response.ok) {
        console.log('success');
        console.log(json);
        setWorkouts(json);
      }
    };

    fetchWorkouts();
  }, []);

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

export default Home;
mzmfm0qo

mzmfm0qo1#

你忘了还了。这样做:

return <p key={workout._id}>{workout.title}</p>;

或者你也可以这样做:

{workouts?.map((workout) => (
        <p key={workout._id}>{workout.title}</p>
    ))}
xqkwcwgp

xqkwcwgp2#

您可以删除贴图上的括号:

workouts.map((workout) => 
        <p key={workout._id}>{workout.title}</p>;
      )}
3df52oht

3df52oht3#

你没有返回任何东西,要么显式地使用return关键字返回元素,要么你可以用更合适的方法来完成。

{
workouts &&
   workouts.map((workout) => (
          <p key={workout._id}>{workout.title}</p>
   ))
}

相关问题