我正在使用最优秀的react-apollo-hooks 库,特别是 useQuery 钩子:
function Index() {
...
const [dialogOpen, setDialogOpen] = useState({ show: false, id: '0' });
...
const { data, error } = useQuery(GET_JOBS, { suspend: true });
if (error) {
return <div>Error! {error.message}</div>;
}
const jobs = data.cxJobs; //This is our data
....
function editCallback(e, more) {
setDialogOpen({ show: true, id: e });
}
....
}
当然,一旦我更改了 dialogOpen 状态,组件就会重新渲染,并且 graphql 查询会再次执行。根据库github repo上的建议,我重写了代码以设置一些状态以及 useEffect:
function Index() {
...
const [dialogOpen, setDialogOpen] = useState({ show: false, id: '0' });
const [jobs, setJobs] = useState([]);
useEffect(_=> {fetchData()}, []);
const fetchData = async _ => {
const result = await client.query({query:GET_JOBS});
setJobs(get(['data','cxJobs'], result));
}
async function onEventChanged(id, event) {
await mutateOne(client, jobGQL, eventToJob(event));
}
...
}
这很不错。但我能做得更好吗?