反应将大代码移动到单独文件中的本机-是钩子吗?

时间:2020-07-09 02:17:13

标签: reactjs react-native react-hooks

我有一个本机屏幕,它的代码很长,我想折射一下。

说我的screen.jsx(当然是简化的):

import React, { useState, useCallback, useEffect } from 'react';
import useLocation from '../hooks/useLocation'; // A custom hook I wrote. This one makes sense to use as a hook. It's a function that returns a location.
...

export default function Screen() {
  const [fetchingLocation, region, setRegion] = useLocation();
  
  // FROM HERE DOWN
  const [fetchingRestaurants, setFetchingRestaurants] = useState(false);
  const [restaurants, setRestaurants] = useState([]);
  const [errorMessage, setErrorMessage] = useState('');

  const initSearch = useCallback(async ({ searchQuery, region }) => {
    setFetchingRestaurants(true);
    try {
      const response = await remoteApi.get('/search', {
        params: {
          term: searchQuery,
          latitude: region.latitude,
          longitude: region.longitude,
        },
      });
      const fetchedRestaurants = response.data.businesses;
      const fetchedRestaurantsArray = fetchedRestaurants.map((restaurant) => ({
        id: restaurant.id,
        name: restaurant.name,
      }));
      setRestaurants(fetchedRestaurantsArray);
      setFetchingRestaurants(false);
    } catch (e) {
      setRestaurants([]);
      setFetchingRestaurants(false);
    }
  }, []);

  return (
    <View>...</View>
  );
}

为了更好地构建我的代码,我想将“ FROM HERE DOWN”(initSearch以及上面的三个状态管理useState钩子)下面看到的所有代码移动到另一个文件中,并将其导入。

此刻,我在 hook 文件夹中创建了一个自定义useRestaurantSearch钩子,如下所示:

export default function useRestaurantSearch() {
  // The code I mentioned goes here
  return [initSearch, errorMessage, restaurants, setRestaurants, fetchingRestaurants];
}

然后在我的Screen.jsx文件中导入import useRestaurantSearch from '../hooks/useRestaurantSearch';,然后在function Screen()内抓取我需要的const s

const [
  initSearch,
  errorMessage,
  restaurants,
  setRestaurants,
  fetchingRestaurants,
] = useRestaurantSearch();

这行得通,但是我觉得可以写得更好,而且整个方法似乎很奇怪-这真的是自定义钩子吗?如果不是自定义钩子,它是否作为实用程序属于util文件夹?

您将如何处理?

0 个答案:

没有答案