0

我在 React Native 中使用https://github.com/FormidableLabs/urql从 GraphQL 服务器获取数据。

这是组件声明:

export default function AddHashtags() {


    const [pattern, setPattern] = useState<string>("")

    const [result, executeQuery] = useSearchHashtagsQuery({
        variables: {
            pattern: pattern
        },
        pause: true
    })

    const { data, fetching, error } = result

    const debounced = _.debounce(() => {
        executeQuery ({ requestPolicy: "network-only"})
    }, 2000)

    useEffect(() => {
        

        debounced()
        return () => debounced.cancel()
    }, [pattern])

    const handleChangeText = (text: string) => {
        setPattern(text)
    }

    return (
        <View>
            <TextInput
                mode="outlined"
                label="#"
                onChangeText={handleChangeText}
            />
            <HashtagList data={data?.searchHashtags} fetching={fetching} error={error} />
        </View>
    )

}

如您所见,查询执行是手动触发executeQuery ({ requestPolicy: "network-only"})的,它根据请求策略绕过缓存。

一开始,查询执行被暂停以避免自动执行:

const [result, executeQuery] = useSearchHashtagsQuery({
    variables: {
        pattern: pattern
    },
    pause: true
})

useEffect挂钩中,executeQuery根据debounce设置,该函数应在 2 秒后执行。

useEffect(() => {
    debounced()
    return () => debounced.cancel()
}, [pattern])

但是,该调用executeQuery ({ requestPolicy: "network-only"})根本不会触发对服务器的查询。

我究竟做错了什么?

HashtagList组件:

interface HashtagListProps {
    data: Hashtag[]
    fetching: boolean
    error?: CombinedError

}

export default function HashtagList({ data, fetching, error }: HashtagListProps) {

    
    if (fetching) {
        return (
            <View>
                <ActivityIndicator animating={true} color={Colors.red800} />
            </View>
        )
    }

    if (error) {
        return (
            <View>
                <FontAwesome5 name="sad-tear" size={24} color="black" />
                <Text>Internet is not available</Text>
            </View>
        )
    }

    return (
        <FlatList
            data={data}
            keyExtractor={item => item.id.toString()}
            renderItem={({ item, index, separators }) => (
                <List.Item
                    title={item.name}
                    key={item.id}
                    right={props => <List.Icon {...props} icon="folder" />}
                />
            )}
        />
    )
}
4

0 回答 0