获取undefined不是函数错误react native

yc0p9oo0  于 2023-04-12  发布在  React
关注(0)|答案(1)|浏览(270)

我一直得到一个“Render error,undefined is not a function”,我不知道是什么原因导致的。

{
     "count": 3,
     "next": "http://0.0.0.0:8000/post?limit=1&offset=1",
     "previous": null,
     "results": [
        {
           "id": 0,
           "title": "title",
           "description": "description",
           "img": "https://linktoimage.jpg"
        }
     ]
}

我的家

const Home = () => {

const { data, isLoading, isError, hasNextPage, fetchNextPage } =
 useFetchPost();
if (isLoading) return <Text>Loading...</Text>; 
if (isError) return <Text>An error occurred while fetching data</Text>;
const flattenData = data.pages.FlatMap((page) => page.data);

const loadNextPageData = () => {
 if (hasNextPage) {
   fetchNextPage();
 }
};

return (

  <FlatList
    keyExtractor={(item) => item.id}
    data={flattenData}
    renderItem={({ item }) => <Post post={item} />}
    estimatedItemSize={2}
    onEndReached={loadNextPageData}
  />
 );
};export default Home;

然后使用FetchPost

import { useInfiniteQuery } from "@tanstack/react-query";
 export default function useFetchPost() {
 const getPosts = async ({ pageParam = 0}) => {
 const res = await (
  await fetch(
    `http://0.0.0.0:8000/post?limit=1&offset=${pageParam}`
  )
).json();   
 
return {
  data: res,
  nextPage: pageParam,
};
};  return useInfiniteQuery(['post'], getPosts, {
getNextPageParam: (lastPage) => {
        if (lastPage.data.length < 1) 
    return undefined;
  return lastPage.nextPage;
},
});
}

最后是错误跟踪:

ERROR  TypeError: undefined is not a function

This error is located at:
    in Home (created by SceneView)
    in StaticContainer
    in EnsureSingleNavigator (created by SceneView)
    in SceneView (created by BottomTabView)
    in RCTView (created by View)
    in View (created by Screen)
    in RCTView (created by View)
    in View (created by Background)
    in Background (created by Screen)
    in Screen (created by BottomTabView)
    in RNSScreen (created by AnimatedComponent)
    in AnimatedComponent
    in AnimatedComponentWrapper (created by InnerScreen)
    in Suspender (created by Freeze)
    in Suspense (created by Freeze)
    in Freeze (created by DelayedFreeze)
    in DelayedFreeze (created by InnerScreen)
    in InnerScreen (created by Screen)
    in Screen (created by MaybeScreen)
    in MaybeScreen (created by BottomTabView)
    in RNSScreenNavigationContainer (created by ScreenContainer)
    in ScreenContainer (created by MaybeScreenContainer)
    in MaybeScreenContainer (created by BottomTabView)
    in RNCSafeAreaProvider (created by SafeAreaProvider)
    in SafeAreaProvider (created by SafeAreaInsetsContext)
    in SafeAreaProviderCompat (created by BottomTabView)
    in BottomTabView (created by BottomTabNavigator)
    in PreventRemoveProvider (created by NavigationContent)
    in NavigationContent
    in Unknown (created by BottomTabNavigator)
    in BottomTabNavigator (created by app)
    in QueryClientProvider (created by app)
    in EnsureSingleNavigator
    in BaseNavigationContainer
    in ThemeProvider
    in NavigationContainerInner (created by app)
    in app (created by withDevTools(app))
    in withDevTools(app)
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in main(RootComponent), js engine: hermes

到目前为止,我已经尝试了多种解决方案,但没有任何工作,我认为它有一个问题,从项目中获取信息,我尝试使用不同的返回,而不是useFetchPost中getNextPageParam中的undefined。

v09wglhw

v09wglhw1#

当您尝试在未定义或不是函数的对象上调用函数时,通常会收到错误消息“TypeError:undefined不是一个函数。”在这种情况下,似乎Home组件是问题的根源。
一个可能的问题可能是从useFetchPost钩子返回的data对象。data对象有一个pages属性,这表明它正在与React Query的useInfiniteQuery钩子一起使用。pages属性是一个页面数组,其中每个页面都有一个包含实际数据的data属性。
然而,在Home组件中,您使用FlatMap展平data数组,但data数组实际上嵌套在每个页面对象中。这意味着flattenData可能不是FlatList所期望的正确格式。
要修复此问题,您可以尝试更新loadNextPageData函数以使用具有正确pageParam值的fetchNextPage。您还可以更新useFetchPost钩子以在返回data数组之前将其展平。以下是代码的更新版本:

import { useInfiniteQuery } from "@tanstack/react-query";

export default function useFetchPost() {
  const getPosts = async ({ pageParam = 0}) => {
    const res = await (
      await fetch(
        `http://0.0.0.0:8000/post?limit=1&offset=${pageParam}`
      )
    ).json();   
 
    return {
      data: res.results, // Flatten the data array
      nextPage: res.next, // Use the correct pageParam value
    };
  };

  return useInfiniteQuery(['post'], getPosts, {
    getNextPageParam: (lastPage) => {
      if (lastPage.nextPage == null) { // Use nextPage instead of data.length
        return undefined;
      }
      return lastPage.nextPage;
    },
    select: (data) => data.pages.map((page) => page.data).flat(), // Flatten the pages array
  });
}

const Home = () => {
  const { data, isLoading, isError, hasNextPage, fetchNextPage } = useFetchPost();

  if (isLoading) return <Text>Loading...</Text>; 
  if (isError) return <Text>An error occurred while fetching data</Text>;

  const loadNextPageData = () => {
    if (hasNextPage) {
      fetchNextPage({
        pageParam: data[data.length - 1].id, // Use the last item's id as pageParam
      });
    }
  };

  return (
    <FlatList
      keyExtractor={(item) => item.id}
      data={data}
      renderItem={({ item }) => <Post post={item} />}
      estimatedItemSize={2}
      onEndReached={loadNextPageData}
    />
  );
};

export default Home;

相关问题