简体   繁体   English

如何将 useEffect 从组件移动到自定义挂钩

[英]How to move useEffect from component to custom hook

I have multiple components with the same useEffect code.我有多个具有相同 useEffect 代码的组件。

fucntion MyComponent1 (props) {

 const {
        handleApiCall,
        data,
        isLoading,
        isError,
        isSuccess,
  } = useCustomAsyncHook();

 React.useEffect(() => {
   if (isSuccess && !isEmpty(data)) {
      setSnackbar({
        show: false,
        message: '',
      });
      dispatch({
        type: ACTION_TYPES.UPDATE_METADATA,
        payload: { data },
      });
    }
 }, [data, isSuccess, setSnackbar]);

 const onSave = () => {
     handleApiCall()
 }

 return (
   <button onClick={onSave}> Save </button>
 )

}

I have this useEffect hook code repeating in multiple components.我有这个useEffect钩子代码在多个组件中重复。 I just want to move this useEffect hook into custom hook so that I need not repeat it in multiple components.我只想将此 useEffect 挂钩移动到自定义挂钩中,这样我就无需在多个组件中重复它。

const useMetadataUpdate = ({ data, isSuccess, setSnackbar, dispatch }) => {
    React.useEffect(() => {
        if (isSuccess && !isEmpty(data)) {
            setSnackbar({
                show: false,
                message: '',
            });
            dispatch({
                type: ACTION_TYPES.UPDATE_METADATA,
                payload: { data },
            });
        }
    }, [data, isSuccess, setSnackbar, dispatch]);
};

fucntion MyComponet1 (props) {
   const {
        handleApiCall,
        data,
        isLoading,
        isError,
        isSuccess,
  } = useCustomAsyncHook();

  useMetadataUpdate({ data, isSuccess, setSnackbar, dispatch });

  const onSave = () => {
     handleApiCall()
 }

 return (
   <button onClick={onSave}> Save </button>
 ) 
}

Refactoring useEffect to a separate function works.useEffect重构为单独的 function 有效。 I can't find documentation explicitly stating a hook needs to return anything, however, I cannot find an example of a hook not returning something.我找不到明确说明挂钩需要返回任何内容的文档,但是,我找不到挂钩不返回任何内容的示例。 Can someone advise on if this approach is correct?有人可以建议这种方法是否正确吗?

The current issue as I can see here is that you have 3 functions namely isEmpty , setSnackbar , and dispatch tightly coupled to your components here.我在这里看到的当前问题是你有 3 个函数,即isEmptysetSnackbardispatch与你的组件在这里紧密耦合。 This restricts you from directly moving this useEffect to your custom hook.这限制了您直接将此useEffect移动到您的自定义挂钩。 The best solution that I can think of right now is moving these functions to a custom hook(you can combine this with context API as well).我现在能想到的最佳解决方案是将这些函数移动到自定义挂钩(您也可以将其与上下文 API 结合使用)。 After that, you can do the following in your custom hook之后,您可以在自定义挂钩中执行以下操作

const useCustomAsyncHook = () => {
  // code to fetch dependenices like `data`, `isSuccess` goes here

  const { setSnackbar, isEmpty, dispatch } = useAnotherCustomHook();

  React.useEffect(() => {
    if (isSuccess && !isEmpty(data)) {
       setSnackbar({
         show: false,
         message: '',
       });
       dispatch({
         type: ACTION_TYPES.UPDATE_METADATA,
         payload: { data },
       });
     }
  }, [data, isSuccess, setSnackbar]);
};

To clean up your component, you can move useEffect to a custom hook that contains the same logic as the original.要清理组件,您可以将useEffect移至包含与原始组件相同逻辑的自定义挂钩。

For example例如

// useCodeSelection.js
...
export const useCodeSelection = () => {
    useEffect(() => {
        console.log('useCodeSelection')
    }
}
...

Then inside your component just call it after you import it, like:然后在你的组件内部,在你导入它之后调用它,比如:

...
useCodeSelection()
...

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

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