如何在事件发生后触发 React Hooks

IT技术 reactjs
2021-05-12 16:27:33

我对 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个回答

如果您不想控制何时触发请求,则必须使用useLazyQueryhttps://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;

我认为您可以useEffect在名称更改时调用钩子内的函数你可以去抖动它,这样它就不会在每次输入字母时都被执行,但是这样的事情应该可以工作:

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

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

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