事件发生后如何触发React Hooks

时间:2019-12-12 16:28:06

标签: reactjs

我对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;

3 个答案:

答案 0 :(得分:1)

如果您不想控制何时触发请求,则必须使用useLazyQueryhttps://www.apollographql.com/docs/react/api/react-hooks/#uselazyquery),例如:

import React, { useState, useLazyQuery } 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 [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;

答案 1 :(得分:0)

我认为只要名称更改,您都可以在useEffect挂钩中调用该函数。您可以将其反跳,这样就不会在每次输入字母时都执行它,但是类似的事情应该起作用:

handleNameChange = (e) => setName(e.target.value);

useEffect(() => {
  const ... = useQuery(...);
}, [name])

答案 2 :(得分:0)

因此,每当名称更改时,您都要触发查询吗?我认为您想要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]);