react-native - React Apollo fetch 一次
问题描述
我正在研究简单的 COVID-19 跟踪器,但我遇到了问题。Apollo 中是否有任何选项可以让 React 每次按下按钮时获取一次 graphql 数据?
现在我有 TextInput 和 Button 但是当我一次获取数据时,我无法在输入中输入另一个国家,因为我立即出错。
const Tile = () => {
const [country, setCountry] = useState('Poland');
const [cases, setCases] = useState(0);
const MY_QUERY = gql`
query getCountryStats($country: String!) {
country(name: $country) {
todayCases
}
}
`;
const [getCountryStats, {data, loading, error}] = useLazyQuery(MY_QUERY, {
variables: {
country: country,
},
onCompleted: (data) => {
setCases(data.country.todayCases);
},
});
if (loading) return <Text>LOADING...</Text>;
if (error) return <Text>Error!</Text>;
return (
<View>
<CasesNumber>{cases}</CasesNumber>
<FinderWrapper>
<FinderInput
onChangeText={(text) => {
setCountry(text);
}}
/>
<FinderButton
onPress={() => {
getCountryStats();
}}>
<Text>FIND</Text>
</FinderButton>
</FinderWrapper>
</View>
);
};
export default Tile;
解决方案
尝试使用这个
const Tile = () => {
const [country, setCountry] = useState('Poland');
const [cases, setCases] = useState(0);
let inputValue = ‘’;
const MY_QUERY = gql`
query getCountryStats($country: String!) {
country(name: $country) {
todayCases
}
}
`;
const [getCountryStats, {data, loading, error}] = useLazyQuery(MY_QUERY, {
variables: {
country: country,
},
onCompleted: (data) => {
setCases(data.country.todayCases);
},
});
const onGetCountryStats = () => {
setCountry(inputValue);
getCountryStats();
}
if (loading) return <Text>LOADING...</Text>;
if (error) return <Text>Error!</Text>;
return (
<View>
<CasesNumber>{cases}</CasesNumber>
<FinderWrapper>
<FinderInput
onChangeText={(text) => {
inputValue = text;
}}
/>
<FinderButton
onPress={() => {
onGetCountryStats();
}}>
<Text>FIND</Text>
</FinderButton>
</FinderWrapper>
</View>
);
};
export default Tile;
推荐阅读
- javascript - Angular 中的更改检测冻结浏览器
- php - 无法使用 symfony 进程从 laravel 运行 python 脚本(退出代码:-1073740791(未知错误))
- jquery - $.parseJSON 错误:JSON 数据的第 1 行第 1 列出现意外字符
- python - 捕获 Argparse 错误并将其传递给 Discord 客户端
- c - 在一个节点中有多个元素的 B 树中递归地找到第 k 个最小的元素
- excel - Excel VBA:无法对重叠选择使用命令
- playframework-2.6 - 在 builds.sbt 和 plugins.sbt 中添加解析器的区别
- java - Spring如何仅通过形式参数名称匹配查询参数?
- php - 从另一个函数调用 PHP 函数
- ios - UIImagePickerController 在 iOS 11 上因“[UIViewController _setCameraOverlayView:]: unrecognized selector”而崩溃