useeffect() 运行 并在 return() 运行 之后将数据设置到变量中?如何处理这个?

useeffect() run and set data to the variable after the return() run in react? how to handle this?

export default function Education() {
  const classes = useStyles();
  const [projects, setProjects] = useState({});

  useEffect(() => {
    axios.get("http://127.0.0.1:8000/api/").then((res) => {
      setProjects(res.data);
      console.log(res.data);
    });
  }, [projects]);

  return (
    <div className={classes.root}>
      <Grid container spacing={3}>
        <Grid item xs={12} sm={12}>
          <Typography variant="h4" color="secondary">
            Some of my work
          </Typography>
        </Grid>

        {projects.map((project) => {
          return <p key={project.id}>{project.name}</p>;
        })}

      </Grid>
    </div>
  );
}

我想在页面呈现时从 api 获取数据,但实际情况是,

  1. 初始化为null的变量项目
  2. return () 运行s 其中 projects.map() 函数是。
  3. 由于项目变量没有任何数据,因此地图对项目 运行 无效。
  4. 然后useeffect()是运行ning.

这就是我收到错误的原因:

TypeError: projects.map 不是函数

我该如何解决这个问题。我是新来的。谁能帮帮我。

将项目的默认值设置为数组,这样它就不会 return 出错:

 const [projects, setProjects] = useState([]);

目前它是一个对象(而不是你所说的 null)。

此外,更新您的 useEffect 并且不要通过 projects:

  useEffect(() => {
    axios.get("http://127.0.0.1:8000/api/").then((res) => {
      setProjects(res.data);
    });
  }, []);

否则它会使您的应用程序崩溃,因为它会创建一个无限循环(如果 projects 不断变化),因为它会在您每次更新项目时触发 useEffect。

useEffect中不需要指定project,直接使用空数组即可。 由于您正在使用 useState 并存储项目的价值。将其保持在 useEffect 上将进行无限次调用。 在使用地图函数时还要检查 projects.length

useEffect(() => {
 axios.get("http://127.0.0.1:8000/api/").then((res) => {
  setProjects(res.data);
  console.log(res.data);
 });
}, []);
 return (
  <div className={classes.root}>
  <Grid container spacing={3}>
    <Grid item xs={12} sm={12}>
      <Typography variant="h4" color="secondary">
        Some of my work
      </Typography>
    </Grid>

    {projects.length && projects.map((project) => {
      return <p key={project.id}>{project.name}</p>;
    })} 

  </Grid>
</div>
);