从正在使用的 API 中获取数据直接在 react 中获取影响或事件处理程序中的数据

在反应钩子中应该如何执行抓取?在这两个代码片段中,哪一个被称为最佳实践或执行 fetch 的最佳反应模式?


此示例用于执行操作。useEffectfetch


import React, { useState, useEffect } from "react";


export default function App() {

  const [query, setQuery] = useState("");

  const [loading, setLoading] = useState(false);

  const [data, setData] = useState([]);


  useEffect(() => {

    if (!loading) return;

    const fetchData = async () => {

      const response = await fetch(

        `https://api.github.com/search/repositories?q=${query}`

      );

      const data = await response.json();

      setData(data.items);

      setLoading(false);

    };

    fetchData();

  }, [loading, query]);


  const onSubmit = e => {

    e.preventDefault();

    setLoading(true);

  };


  return (

    <div className="App">

      <h1>Search Github Repo.</h1>

      <h3>Implementation One</h3>

      <form onSubmit={onSubmit}>

        <input

          type="text"

          value={query}

          onChange={e => setQuery(e.target.value)}

        />

        <button type="submit">Search</button>

      </form>

      {loading && <div>Loading...</div>}

      {!loading &&

        data.map(repo => (

          <div key={repo.id}>

            <h4>{repo.name}</h4>

            <p>{repo.description}</p>

          </div>

        ))}

    </div>

  );

}

此示例使用事件处理程序来执行操作。onClickfetch


import React, { useState } from "react";


export default function App() {

  const [query, setQuery] = useState("");

  const [loading, setLoading] = useState(false);

  const [data, setData] = useState([]);


  const onSubmit = e => {

    e.preventDefault();

    setLoading(true);

    const fetchData = async () => {

      const response = await fetch(

        `https://api.github.com/search/repositories?q=${query}`

      );

      const data = await response.json();

      setData(data.items);

      setLoading(false);

    };

    fetchData();

  };


}


ibeautiful
浏览 64回答 2
2回答

智慧大石

这取决于您的用例,您应该采取哪种方法在以下情况下获取数据很有用useEffect在某些生命周期(如初始渲染)中获取数据在某些 prop 更改时获取数据每隔一段时间获取数据,但设置订阅或setInterval在下面的方案中,在处理程序中获取数据很有用根据用户交互(如搜索按钮单击)、搜索输入更改由于您的案例是基于使用交互的,因此在处理程序而不是钩子中实际调用API会更好,更受控制useEffect

GCT1015

我会说你应该使用钩子实现。在 React 文档中,建议使用它来执行副作用:数据获取、设置订阅和手动更改 React 组件中的 DOM 都是副作用的示例。无论您是否习惯于将这些操作称为“副作用”(或只是“效果”),您之前都可能在组件中执行过它们。(链接到报价)还有一个需要考虑的因素。在钩子实现中:useEffect(() => {&nbsp; &nbsp; if (!loading) return;&nbsp; &nbsp; const fetchData = async () => {&nbsp; &nbsp; &nbsp; const response = await fetch(&nbsp; &nbsp; &nbsp; &nbsp; `https://api.github.com/search/repositories?q=${query}`&nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; const data = await response.json();&nbsp; &nbsp; &nbsp; setData(data.items);&nbsp; &nbsp; &nbsp; setLoading(false);&nbsp; &nbsp; };&nbsp; &nbsp; fetchData();&nbsp; }, [loading, query]);您使用了优化。您正在传递到钩子中,这意味着该函数仅在其中一个值更改时运行。在第二个实现中,您将在每个输入更改上运行获取[loading, query]以下是关于钩子这一方面的 React 文档的链接。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript