【问题标题】:How to avoid constantly calling api?如何避免不断调用api?
【发布时间】:2021-10-11 05:22:21
【问题描述】:

如何避免不断调用API?我想避免这种情况,以便在调用时不会对 API 施加压力

useEffect(
  React.useCallback(  () => {
    const task = InteractionManager.runAfterInteractions( async () => {
      const _token =  await AsyncStorage.getItem('@token');
      let UserId = await AsyncStorage.getItem('@UserID')
      setToken(_token);
      fetchParents(UserId, _token);
      fetchStudent(UserId, _token);
      fetchTeacher(UserId, _token);
      UserProfile(UserId, _token)
    });
    return () => task.cancel();
  }, [])
); 


const fetchParents = async (UserId, _token) => {
  try {
    fetch(config.API_URL + '/Parents/Application/Access/10/'+UserId, {
      method: 'GET',
      headers: {
        //Headers
        'Authorization': 'Bearer '+ _token,
        'Content-Type': 'application/json',
      },
    })
    .then((response) =>  response.json().then(data=>({status:response.status, body:data})) )
    .then((response) => {
      if(response.status==200)
      {
        if(response.body.length > 0)
        {
          setParent(response.body[0].udf_Users_IsHaveApplicationAccess)
        }else{
          console.log("err");
        }
      }else{
        console.log("error");
      } 
    });
  
  } catch (e) {
    console.log(e);
  }
}
const fetchStudent = async (UserId, _token) => {
    .....//same code in fetchParents
}
const fetchTeacher = async (UserId, _token) => {
    .....//same code in fetchParents
}
const UserProfile = async (UserId, _token) => {
    .....//same code in fetchParents
}

【问题讨论】:

    标签: javascript react-native react-hooks


    【解决方案1】:

    您以错误的方式使用了useCallabck 钩子,此钩子不需要return 语句来清理。有关 React 的 useCallabck 文档的更多信息。

    首先,尝试从useCallback 中删除return 语句。然后尝试在 useEffect 之外实现回调:

    const [task, setTask] = useState(null); // initialize with proper data or leave it blank
    
    const fetchData = React.useCallback(  () => {
        const newTask = InteractionManager.runAfterInteractions( async () => {
          const _token =  await AsyncStorage.getItem('@token');
          let UserId = await AsyncStorage.getItem('@UserID')
          setToken(_token);
          fetchParents(UserId, _token);
          fetchStudent(UserId, _token);
          fetchTeacher(UserId, _token);
          UserProfile(UserId, _token)
        });
        setTask(newTask)
      }, [])
    
    
    // now, this useEffect run only once after your component did mount
    useEffect( () => {
        fetchData()
        // to cleanup tasks on component will mount
        return () => {
          task.cancel();
          setTask(null)  // to remove task from state
      }, [])
    );
    
    

    此外,您可以使用不带 useCallback 挂钩的异步函数调用您的 API(我猜您曾经忽略了 useEffect 中的异步调用)

    async function fetchData () {
      try {
          const newTask = InteractionManager.runAfterInteractions( async () => {
            const _token =  await AsyncStorage.getItem('@token');
            let UserId = await AsyncStorage.getItem('@UserID')
            setToken(_token);
            fetchParents(UserId, _token);
            fetchStudent(UserId, _token);
            fetchTeacher(UserId, _token);
            UserProfile(UserId, _token)
          });
          setTask(newTask)
      } catch (error) {
       // do somethings with error case
      }
    }
    

    【讨论】:

    猜你喜欢
    • 2014-11-24
    • 1970-01-01
    • 2022-08-09
    • 2021-10-04
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多