无论如何要避免在反应钩子依赖数组?

时间:2020-05-15 15:42:26

标签: javascript reactjs react-hooks use-effect

我有一个功能组件,可以说Offer。此组件在加载时称为api api_1。一旦收到api_1的响应并成功,我想触发另一个api调用说api_2,并基于api_2的响应想显示success screen否则{{1 }}。另外,万一error screen失败了,我想显示api_1

error screen

现在,只要有const Offers =()=>{ const[api_1Success,setApi_1Success]=useState(null); const[api_1Failure,setApi_1Failure]=useState(null); const[api_1FetchComplete,setApi_1FetchComplete]=useState(null); const[api_2Success,setApi_2Success]=useState(null); const[api_2Failure,setApi_2Failure]=useState(null); const[api_2FetchComplete,setApi_2FetchComplete]=useState(null); const showSuccess =useCallback(() =>{ //sets some other state to render success page },[api_2Success]); const showError =useCallback(() =>{ //sets some other state to render error page },[]); const changeScreen = useCallback(() => { if(api_2Success){ showSuccess(); } else { showErrorScreen(); } },[api_2Success,showSuccess,showErrorScreen]); useEffect(()=>{ /** first useEffect **/ //dummy api call dummyApiCall().then((response)=>{ setApi_1Success(response); }).catch(ex=>(setApi_1Failure(ex))).finally(()=>(setApi_1FetchComplete(true))); },[]) useEffect(()=>{ /** second useEffect **/ if(api_1FetchComplete){ if(api_1Success){ //dummy api call dummyApiCall().then((response)=>{ setApi_2Success(response); }).catch(ex=>(setApi_2Failure(ex))).finally(()=>(setApi_2FetchComplete(true))); } } if(api_1Failure){ changeScreen(); } },[ api_1FetchComplete, api_1Failure, api_1Success, changeScreen, ]) useEffect(()=>{ /** third useEffect **/ if(api_2FetchComplete){ changeScreen(); } },[api_2FetchComplete,changeScreen]); return(....); } 的响应可用,第三次useeffect就会运行,结果changeScreen方法会根据api_2的变化而更改。现在,由于changeScreen已更改,因此第二次useEffect被调用,并且循环继续。 / p>

有什么原因可以避免在依赖项数组中添加changeScreen

1 个答案:

答案 0 :(得分:0)

创建async/await函数可以帮助更好地创建和理解异步流:

  useEffect(() => {
    const getResponses = async () => {
      try {
        const response = await dummyApiCall();
        setApi_1Success(response);

        const response2 = await dummyApiCall();
        setApi_2Success(response2);
      } catch (error) {
        changeScreen();
      }
    };

    getResponses();
  }, []);