簡體   English   中英

無效的鈎子調用 React

[英]Invalid hook call React

https://reactjs.org/docs/hooks-custom.html構建自己的 Hooks 可以讓您將組件邏輯提取到可重用的函數中。 這就是我想要做的:將我的組件邏輯提取到其他組件的可重用函數中。

我的功能組件:

//React
import React from 'react';
import { FlatList, View, Text, StyleSheet } from 'react-native';
//Local
import UserPreview from './UserPreview';
import defaultContainer from '../../shared/styles/defaultContainer';
import useFetchUsers from './../../../handler/useFetchUsers';

export default function UserList(props) {
    const { users } = props;
    const dispatch = useDispatch();
    //State
    const [isLoading, setIsLoading] = React.useState(false);
    const [error, setError] = React.useState(null);

    return (
        <View style={defaultContainer}>
            <FlatList
                data={users}
                keyExtractor={(item) => item.id}
                renderItem={({ item }) => <UserPreview user={item} />}
                ListEmptyComponent={() => <Text style={styles.listEmpty}>Keine Benutzer gefunden!</Text>}
                ItemSeparatorComponent={() => <View style={styles.listSeperator} />}
                onRefresh={useFetchUsers}
                refreshing={isLoading}
                contentContainerStyle={styles.container}
            />
        </View>
    );
}

我的可重復使用的 function:

import React from 'react';
import * as userActions from '../store/actions/user';
import { useDispatch } from 'react-redux';

export default async function useFetchUsers() {
    const [error, setError] = React.useState(null);
    const dispatch = useDispatch();
    const [isLoading, setIsLoading] = React.useState(false);

    console.log('StartupScreen: User laden');
    setIsLoading(true);
    setError(null);
    try {
        await dispatch(userActions.fetchUsers());
        console.log('StartupScreen: User erfolgreich geladen');
    } catch (err) {
        setError(err.message);
    }
    setIsLoading(false);
}

我應該如何在我的用戶列表的 onRefresh 屬性中使用我的 function? 我收到此錯誤:無效的掛鈎調用在此處輸入圖像描述

您正在使用useFetchUsers作為回調。 鈎子規則禁止這樣做。

useFetchUsers應該返回一些可以用作回調的 function:

export default function useFetchUsers() {
    const [error, setError] = React.useState(null);
    const dispatch = useDispatch();
    const [isLoading, setIsLoading] = React.useState(false);

    return async function() {
        console.log('StartupScreen: User laden');
        setIsLoading(true);
        setError(null);
        try {
            await dispatch(userActions.fetchUsers());
            console.log('StartupScreen: User erfolgreich geladen');
        } catch (err) {
            setError(err.message);
        }
        setIsLoading(false);
    }
}


function UserList(props) {

    ...

    const handleRefresh = useFetchUsers();

    ...

    return <FlatList onRefresh={handleRefresh} />;
}

React 鈎子不能是異步 function。 所以根據這個 redux 工作流程: 在此處輸入圖像描述

您必須調度 fetch 用戶的操作,然后您的加載和錯誤狀態應該在您的減速器中,如果您在 redux 旁邊有任何副作用管理器,例如 redux-saga,您必須調用所有 HTTP 方法,並且您的組件應該發送並展示結果。 另一種方法是調用並獲取用戶到您的鈎子中,並通過您調度的操作將它們放入您的 redux 存儲中。 這樣,加載和錯誤可以在您的掛鈎中(在您的本地掛鈎 state 中,而不是在 redux-store 中)。

所以讓我們試試這段代碼(我已經實現了第二種方式):

import React from 'react';
import * as userActions from '../store/actions/user';
import { useDispatch } from 'react-redux';

export default function useFetchUsers() {
    const [error, setError] = React.useState(null);
    const dispatch = useDispatch();
    const [isLoading, setIsLoading] = React.useState(false);
    
    React.useEffect(() => {
      (async () => {
          console.log('StartupScreen: User laden');
          setIsLoading(true);
          setError(null);
          try {
              const res = await fetchUsers();

              dispatch(setUsers(res.data));
              console.log('StartupScreen: User erfolgreich geladen');
              setIsLoading(false);
          } catch (err) {
              setIsLoading(false);
              setError(err.message);
          }
      })()
    }, [])
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM