对于React和如何使用钩子,我还是个新手。我知道下面的代码不能工作,但我写它是为了显示我想要实现的东西。基本上,我想在输入框中发生变化后使用useQuery,这是不允许的(在钩子或事件中使用钩子)。
那么如何使用react钩子正确地实现这个用例呢?我想在用户输入时从GraphQL加载数据。
import React, { useState, useQuery } from "react";
import { myGraphQLQuery } from "../../api/query/myGraphQLQuery";
// functional component
const HooksForm = props => {
// create state property 'name' and initialize it
const [name, setName] = useState("Peanut");
const handleNameChange = e => {
const [loading, error, data] = useQuery(myGraphQLQuery)
};
return (
<div>
<form>
<label>
Name:
<input
type="text"
name="name"
value={name}
onChange={handleNameChange}
/>
</label>
</form>
</div>
);
};
export default HooksForm;发布于 2019-12-13 02:30:28
如果不想控制何时触发请求,则必须使用useLazyQuery (https://www.apollographql.com/docs/react/api/react-hooks/#uselazyquery),如下所示:
import React, { useState } from "react";
import { useLazyQuery } from "@apollo/client";
import { myGraphQLQuery } from "../../api/query/myGraphQLQuery";
// functional component
const HooksForm = props => {
// create state property 'name' and initialize it
const [name, setName] = useState("Peanut");
const [doRequest, { called, loading, data }] = useLazyQuery(myGraphQLQuery)
const handleNameChange = e => {
setName(e.target.value);
doRequest();
};
return (
<div>
<form>
<label>
Name:
<input
type="text"
name="name"
value={name}
onChange={handleNameChange}
/>
</label>
</form>
</div>
);
};
export default HooksForm;发布于 2019-12-13 00:40:59
我认为只要名称更改,就可以在useEffect钩子中调用该函数。你可以去掉它,这样它就不会在每次输入字母时被执行,但是像这样的东西应该可以工作:
handleNameChange = (e) => setName(e.target.value);
useEffect(() => {
const ... = useQuery(...);
}, [name])发布于 2019-12-13 00:42:20
那么,每当名称更改时,您希望触发查询吗?我想你想要useEffect。
const handleNameChange = e => setName(e.target.value);
useEffect(() => {
// I'm assuming you'll also want to pass name as a variable here somehow
const [loading, error, data] = useQuery(myGraphQLQuery);
}, [name]);https://stackoverflow.com/questions/59308941
复制相似问题