reactjs - 根据条件响应 Apollo Query
问题描述
我目前正在构建一个应用程序(混合移动应用程序)来显示记录(地点)列表。以下是我的要求,
1)如果应用程序是online
,从服务器获取详细信息。
2)如果应用程序是offline
,从本地存储中获取详细信息。
我可以让每个条件自己工作。但是(我对 react 和 apollo-react 还很陌生),我不确定如何向查询添加条件。
下面是我从服务器获取数据的查询示例(我有这部分工作)
const client = new ApolloCient({
uri: "/graphql"
});
const PLACES_LIST = gql`
{
places {
id
title
}
}
`;
class PlacesList extends React.Component {
render() {
return (
<ApolloProvider client={client}>
<Query query={PLACES_LIST}>
{({ loading, data }) => {
if (loading) return "Loading....";
const { places } = data;
return places.map(place => (
<PlaceDetail
key={place.id}
place={place}
></PlaceDetail>
));
}}
</Query>
</ApolloProvider>
);
}
}
我想这个的伪代码是,
if (online) {
# run apollo client
} else {
# read from the local storage
}
谁能指出我正确的方向。TIA。
此外,我正在使用最新版本的 react,如果需要,我可以灵活地使用 react 钩子。
解决方案
const client = new ApolloCient({
uri: "/graphql"
});
const PLACES_LIST = gql`
{
places {
id
title
}
}
`;
class PlacesList extends React.Component {
render() {
return (
<ApolloProvider client={client}>
<Query query={PLACES_LIST}>
{({ loading, data, error }) => {
// There is also an error parameter from the hook
if (loading) return "Loading....";
// Here You can decide if its a connection error or smt other.
// I would recoment the fetchPolicy="network-only" prop for your <Query> in this case
if(error) {
return localstorage.getItem("Smt");
} else {
const { places } = data;
return places.map(place => (
<PlaceDetail
key={place.id}
place={place}
></PlaceDetail>
));
}
}}
</Query>
</ApolloProvider>
);
}
}
推荐阅读
- c# - 具有 InverseProeprty 的同一集合实体框架 6 上的多对多和一对多
- docker - 为什么 Docker compose 需要很长时间才能在 Windows 中构建?
- drools - jbpm 进程未使用 ruleFlowGroup 触发流口水规则
- google-apps-script - 使用 DriveApp 移动文件或文件夹
- ios - iOSDropDown 不识别水龙头
- python - 制表键是否未向 PyQt5 注册?
- c++ - QString中是否有任何等效的swprintf?
- rest - 创建 ABAP REST 类以查询多个实体
- nativescript - 当我无法找到北方向时,如何在 nativescript 中制作指南针?
- javascript - 检查选项是否存在的更短方法