【问题标题】:displaying only one entry with useQuery使用 useQuery 只显示一个条目
【发布时间】:2021-09-18 07:39:42
【问题描述】:

我试图只显示查询中的一个值,我想知道为什么代码的第一个 sn-p 不显示名称而另一个显示名称

这个不行:

const EXCHANGE_RATES = gql`
  query {
    profiles (limit: 1){
        id
        name
  }
}
`;

export const ExchangeRates: React.FC<ExchangeRatesProps> = () => {
    const { loading, error, data } = useQuery(EXCHANGE_RATES);

    if (loading) return <Text>Loading...</Text>;
    if (error) return <Text>Error :(</Text>;
    
    return  (
        <View >
            <Text>
                {data.profiles.name}
            </Text>
        </View>
    );
}

但是这个可以:

export const EXCHANGE_RATES = gql`
  query {
    profiles (limit: 1){
        id
        name
  }
}
`;

export const ExchangeRates: React.FC<ExchangeRatesProps> = () => {
    const { loading, error, data } = useQuery(EXCHANGE_RATES);

    if (loading) return <Text>Loading...</Text>;
    if (error) return <Text>Error :(</Text>;


    return data.profiles.map(({ id, name} : {id:number, name:string}) => (
        <View >
            <Text>
                {id} : {name}
            </Text>
        </View>
    ));
}

【问题讨论】:

  • useQuery返回的数据是数组吗?

标签: typescript react-native react-hooks


【解决方案1】:

data.profiles 是一个数组。您必须执行data.profiles[0].name 之类的操作。如果你这样做 console.log(data.profiles) 你会看到它是一个数组

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 2013-05-13
    • 1970-01-01
    • 2021-11-20
    • 2017-05-18
    • 1970-01-01
    相关资源
    最近更新 更多