【问题标题】:React Custom Hooks - Is it correct to implement stateful hooks?React Custom Hooks - 实现有状态的钩子是否正确?
【发布时间】:2021-10-12 12:56:08
【问题描述】:

我正在重构我的应用程序的一些组件,我决定将一些逻辑移动到钩子中,以使代码更简单和可重用。

例如:

export default function useMediaLibrary() {
  const isMounted = useIsMounted();

  const [images, setImages] = useState([]);

  const isFetching = useRef(false);
  const cursor = useRef(null);

  const fetchImages = async (limit = 60) => {
    if (isFetching.current) return;

    isFetching.current = true;

    const results = await MediaLibrary.getAssetsAsync({
      first: limit,
      after: cursor.current,
      sortBy: MediaLibrary.SortBy.creationTime,
      mediaType: [MediaLibrary.MediaType.photo],
    });

    if (!isMounted()) return;

    const { assets, hasNextPage, endCursor } = results;

    setImages(images.concat(assets));

    cursor.current = hasNextPage ? endCursor : null;

    isFetching.current = false;
  };

  const fetchNextImages = (limit = 60) => {
    // Necessary condition to avoid loops
    if (cursor.current) {
      fetchImages(limit);
    }
  };

  const createAsset = (uri) => MediaLibrary.createAssetAsync(uri);

  const requestPermissions = (writeOnly = false) =>
    MediaLibrary.requestPermissionsAsync(writeOnly);

  return {
    images,
    fetchFirstImages: fetchImages,
    fetchNextImages,
    createAsset,
    requestPermissions,
  };
}

如你所见,这个钩子有点复杂……它依赖于其他钩子,也管理着一些状态。

这是我的问题:在自定义钩子中管理状态是一种好习惯还是我们应该避免它?

【问题讨论】:

    标签: reactjs react-native react-hooks


    【解决方案1】:

    是的,钩子用于提取包括状态在内的逻辑。见here

    【讨论】:

      猜你喜欢
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2020-04-26
      • 1970-01-01
      • 2020-01-17
      相关资源
      最近更新 更多