【发布时间】:2020-09-21 10:36:40
【问题描述】:
我一直在使用 client.query 从我的数据库中获取数据并使用 useState 设置状态。
这是一个例子:
const [videos, setVideos] = useState([]);
client.query({ query: GET_VIDEOS })
.then(response => {
setVideos(response.data.videos);
})
但是,这不会 100% 加载。通常,当我第一次加载应用程序时它不会加载。在这些情况下,我通常必须重新启动。
这个问题让我想研究 useQuery 而不是 client.query。
但是,文档中的示例仅展示了我们如何使用 useQuery 对组件进行直接更改。
例子:
function Dogs({ onDogSelected }) {
const { loading, error, data } = useQuery(GET_DOGS);
if (loading) return 'Loading...';
if (error) return `Error! ${error.message}`;
return (
<select name="dog" onChange={onDogSelected}>
{data.dogs.map(dog => (
<option key={dog.id} value={dog.breed}>
{dog.breed}
</option>
))}
</select>
);
}
但是,我现在不想更改组件。我更愿意查询数据,然后使用 useState 将查询的数据设置为状态。
我将如何最好地做到这一点?我的一个想法是创建一个返回 null 但查询数据的组件。它看起来像这样:
function Videos() {
const { loading, error, data } = useQuery(GET_VIDEOS);
if (loading) return 'Loading...';
if (error) return `Error! ${error.message}`;
setVideos(data);
return null;
}
我很想知道在这种情况下有哪些最佳做法。
【问题讨论】:
标签: react-native expo apollo react-apollo