useEffect

时间:2021-05-08 23:00:53

标签: reactjs react-hooks

我想运行从另一个数据(API)解构的数据(所有级别)并将其显示到 dom 中,它可以工作,但是当我刷新页面时得到一个空数组

通过下面的代码我得到了数据

//Function to fetch the data from the API
  const GetCourses = async () => {
    const response = await axios.get(url)
    const {data} = response;
    return data;
  }

//UseEffect to run the function on every render
  useEffect(()=> {
    const GetCoursesYoga = async () => {
      const result = await GetCourses();
      setYogaCourses(result);
      setTimeout(() => {setIsLoading(false)}, 1000);
    } 
    GetCoursesYoga();
  }, []);

从上面的数据中我想得到所有带有级别名称的项目(初学者-中级)

const allLevels = [ ...new 
   Set(yogaCourses.map((singleLevel)=> 
   singleLevel.level))];

我从数组中获得了一个特定项目的数组,我想以下面的状态存储

const [levels, setLevels] = useState([]);


useEffect(()=> {
    setLevels(allLevels);
  },[])

如何在我的状态 setLevels 中存储数组 allLevels ?假设yogaCourses处于状态

谢谢

1 个答案:

答案 0 :(得分:1)

当您从 API 获得结果时,您可以将其直接设置为您的 useState

useEffect(()=> {
    const GetCoursesYoga = async () => {
      const courses = await GetCourses();
      setYogaCourses(courses.map(course => course.level));
      setTimeout(() => {setIsLoading(false)}, 1000);
    } 
    GetCoursesYoga();
  }, []);

假设你也有这个: const [yogaCourses, setYogaCourses] = useState([])

此外,setTimeout(() => {setIsLoading(false)}, 1000); 也不是很好。 我们可以做的是等到我们真正得到结果并设置useState。所以当我们的 courses[] => ['course1', 'course2'...]

所以我们可以做的是:(当我们的yogacourses改变值时,如果该值大于0,我们假设我们有一些响应,我们可以停止加载)

    useEffect(()=> {
      if(yogaCourses.length > 0){
        setIsLoading(false)
      }
    }, [yogaCourses]);