React自定义钩子

时间:2020-05-26 12:04:08

标签: reactjs react-native

我正在尝试从屏幕上的钩子组件中提取逻辑,但是没有加载数据。我想将我的自定义钩子组件用于其他屏幕,并且我不想再重复一遍。因此,我无法弄清楚错误的出处或是否有其他解决方法。我只想挂钩即可在Flatlist中显示数据。

主屏幕:

        import React, { useEffect, useState} from 'react';
        import { FlatList, View, StyleSheet, Text, StatusBar} from 'react-native';
        import {ListItem}from 'react-native-elements'
        import ResultList from '../src/Components/ResultList';
        import useResults from '../src/Hooks/useResults';


        const News = () => {
          const [loadData, book] = useResults([]);



        return(
          <View >
          <FlatList
            paddingTop={10}
            data={book}
            renderItem={({item}) => 
            <View style={{height: 60}}>
            <ListItem 
            title={item.volumeInfo.title}
            leftAvatar={{source: {uri: item.thumbnail}}}
            bottomDivider
            topDivider
            chevron
            titleStyle={{fontSize:15,flex: 1, justifyContent:'center',  }}
            onPress={() => navigation.navigate('Detail', item.volumeInfo, item.saleInfo)}
            />
            </View>
            }
            keyExtractor={(item) => item.id}
          />

        </View>
      )

          }

        export default News;

这是我的useResults组件:

        import { useEffect, useState, useCallback } from 'react';

        const API_KEY = ''
        const Q = 'search+terms';
        const API_URL = `https://www.googleapis.com/books/v1/volumes?key=${API_KEY}&q=${Q}`;

        const useResults = () =>{

        const [book, setBook] = useState({items:[], });


        const loadData = async () => {
            const response = await fetch(API_URL);
            const data = await response.json();
            setBook(data.items)
            console.log(data.items)
        }


            useEffect (() => {
                loadData(); 
            }, []);

            return [book, loadData];

        };

        export default useResults;

0 个答案:

没有答案