简体   繁体   English

在 axios 函数调用中设置状态,然后在 useEffect 钩子中调用函数

[英]Setting state inside of axios function call, then call function in useEffect hook

I am using React functional components.我正在使用 React 功能组件。 I am setting state inside of an axios call, then calling the function in useEffect hook.我在 axios 调用中设置状态,然后在 useEffect 挂钩中调用该函数。

Here is my function:这是我的功能:


import { useDispatch } from “react-redux”;

functon ABCComponent({ navigation }){

    const dispatch = useDispatch();
   
    const testPostID = "1234567891011";
    
    const [post, setPost] = useState("");

     const getPostById = async(postID)=>{
        await axios.get(`http://localhost:5000/posts/post/${postID}`)
            .then((response) =>{
                dispatch(setLoading(true));
                dispatch(setSuccess(true));
                dispatch(setLoading(false));
                response.data.message.map((post, index) =>{
            
                    setPost(post); // I think it's complaining about this line
                });
            }).catch((error) =>{
                console.log("err: ", error);
                dispatch(setLoading(true));
                dispatch(setSuccess(false));
                dispatch(setLoading(false));
                dispatch(setMessage(`${error}`));
            });
    };

    useEffect(() =>{
        getPostById(testPostID);
    }, []);
    
}

I am getting the following error:我收到以下错误:

Warning : Can't perform a React state update on an unmounted component.警告:无法对未安装的组件执行 React 状态更新。 This is a no-op, but it indicates a memory leak in your application.这是一个空操作,但它表明您的应用程序中存在内存泄漏。 To fix, cancel all subscriptions and asynchronous tasks in %s.%s, a useEffect cleanup function, in ABCComponent.要解决此问题,请取消 %s 中的所有订阅和异步任务。%s 是 ABCComponent 中的一个 useEffect 清理函数。

What I tried: I tried removing async/await hoping that it would solve the problem, but it didn't.我尝试了什么:我尝试删除 async/await 希望它能解决问题,但它没有。

what is the best way to go about solving this?解决这个问题的最佳方法是什么?

Memory leak can occur when you are trying to update state on unmounted component, like the warning said.当您尝试更新未安装组件的状态时,可能会发生内存泄漏,如警告所述。 In order to fix this you should include some isMounted flag that you will use in order to check whether component is still mounted, before updating state.为了解决这个问题,您应该包含一些isMounted标志,您将使用该标志来检查组件是否仍在安装,然后再更新状态。 Also there are few other suggests I would give you - do not use async/await with .then, you should use only one of these two approach(async/await is my suggestion).此外,我会给你的其他建议很少 - 不要将 async/await 与 .then 一起使用,你应该只使用这两种方法中的一种(async/await 是我的建议)。

You should rewrite to something like this:您应该重写为这样的内容:

const isMounted = useRef(true);
const testPostID = "1234567891011";

const [post, setPost] = useState("");

const getPostById = async(postID)=>{
      try {
        dispatch(setLoading(true));

        const response = await axios.get(`http://localhost:5000/posts/post/${postID}`)
        
        if(isMounted.current){
            dispatch(setSuccess(true));
            dispatch(setLoading(false));
            response.data.message.map((post, index) =>{
                 setPost(post); // This part is unclear, why overriding state, and why in .map???
            });
         }
       } catch(err) {
         console.log("err: ", error);
         if(isMounted.current) {              
           dispatch(setLoading(true));
           dispatch(setSuccess(false));
           dispatch(setLoading(false));
           dispatch(setMessage(`${error}`));
         }
       }
  };

useEffect(() =>{
    getPostById(testPostID);

   return () => {
     isMounted.current = false;
   }
}, []);

Also there is one unclear part where you are updating state, why using .map and why overriding state in each iteration?还有一个不清楚的部分是在哪里更新状态,为什么使用 .map 以及为什么在每次迭代中覆盖状态?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM