【问题标题】:useeffect() run and set data to the variable after the return() run in react? how to handle this?useeffect() 在react 中运行return() 后运行并将数据设置为变量?如何处理?
【发布时间】:2021-08-24 11:03:45
【问题描述】:
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 () 在 projects.map() 函数所在的位置运行。
  3. 由于项目变量没有任何数据,因此地图不是在项目上运行的有效函数。
  4. 然后 useeffect() 正在运行。

这就是为什么我得到错误:

TypeError:projects.map 不是函数

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

【问题讨论】:

    标签: reactjs react-hooks react-functional-component


    【解决方案1】:

    你不需要在 useEffect 中指定项目,只需使用一个空数组即可。 由于您正在使用 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>
    );
    

    【讨论】:

    • 确定检查长度确实很有帮助。我认为现在它不会出现错误并等待数据被调用。其次,我使用 [projects] 作为参数传递,而不是使用它来交替呈现数据。但使用它作为参数工作正常。谢谢
    【解决方案2】:

    将项目的默认值设为数组,这样它就不会返回错误:

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

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

    另外,更新您的useEffect,不要传递projects

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

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

    【讨论】:

    • 1st,我得到了 json 格式,所以我该如何设置它的默认值。并且设置一个默认值将帮助我获得我真正想要的数据。第二,我尝试从 [] 中删除项目,它也没有帮助。有时它会在控制台返回数据,有时它不会。
    • 那么你需要有一个 res.data 的后备
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 2021-03-15
    • 2018-05-01
    • 1970-01-01
    • 2021-12-30
    • 2022-11-03
    • 1970-01-01
    相关资源
    最近更新 更多