如何使用 React hooks handle/chain 依赖于另一个的同步副作用

How to handle/chain synchronous side effects that depend on another with React hooks

我正在尝试将我的应用程序从 redux 重写为新的 context + hooks,但不幸的是,我很难找到一种好方法来处理一系列同步副作用,这些副作用取决于上一个。

在我当前的 redux 应用程序中,我大量使用 synchronous/chained 操作和 API 请求,我通常通过 redux-saga 或 thunk 处理它们。因此,当返回第一个 API 请求的响应时,该数据将用于下一个 API 请求等

我做了一个自定义挂钩 "useFetch"(在这个例子中它没有做太多,因为它是一个简化版本,我还必须做一个小的调整才能在 codesandbox 上工作 - 请参阅下面的代码)。问题在于,由于 "rules of hooks",我无法在 useEffect 挂钩内使用自定义挂钩。那么,如果您有自己的获取数据的钩子,如何在执行下一个请求之前等待第一个请求的响应呢?即使我最终放弃了 useFetch 抽象并创建了一个普通的获取请求,如何避免以许多 useEffects 挂钩的臃肿混乱结束?这可以做得更优雅一点,还是上下文 + 钩子与 redux saga/thunk 竞争处理副作用还为时过早?

下面的示例代码非常简单。它应该尝试模拟的是:

  1. 查询人物 api 获取人物的端点
  2. 一旦我们有了这个人 响应,查询工作端点(使用现实世界中的人员 ID 情景)
  3. 一旦我们有了人和工作,基于响应 从 person 和 job 端点,查询 collegues 端点到 找到特定工作的同事。

这是代码。为 useFetch 钩子添加延迟以模拟现实世界中的延迟:

import React, { useEffect, useState } from "react";
import { render } from "react-dom";

import "./styles.css";

const useFetch = (url, delay = 0) => {
  const [data, setData] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      // const result = await fetch(url, {
      //  method: "GET",
      //  headers: { "Content-Type": "application/json" }
      // });
      //const response = await result.json();
      const response = await import(url);
      setTimeout(function() {
        setData(response);
      }, delay);
    };

    fetchData();
  }, [url]);

  return data;
};

function App() {
  const [person, setPerson] = useState();
  const [job, setJob] = useState();
  const [collegues, setCollegues] = useState();

  // first we fetch the person /api/person based on the jwt most likely
  const personData = useFetch("./person.json", 5000);
  // now that we have the person data, we use the id to query for the
  // persons job /api/person/1/jobs
  const jobData = useFetch("./job.json", 3000);
  // now we can query for a persons collegues at job x /api/person/1/job/1/collegues
  const colleguesData = useFetch("./collegues.json", 1000);

  console.log(personData);
  console.log(jobData);
  console.log(colleguesData);

  // useEffect(() => {
  //   setPerson(useFetch("./person.json", 5000));
  // }, []);

  // useEffect(() => {
  //   setJob(useFetch("./job.json", 3000));
  // }, [person]);

  // useEffect(() => {
  //   setCollegues(useFetch("./collegues.json",1000));
  // }, [job]);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

const rootElement = document.getElementById("root");
render(<App />, rootElement);

运行 示例:https://codesandbox.io/s/2v44lron3n?fontsize=14(您可能需要进行更改 - space 或删除分号 - 才能生效)

希望这样的事情(或更好的解决方案)是可能的,否则我将无法从令人敬畏的 redux-saga/thunks 迁移到 context + hooks。

最佳答案: https://www.youtube.com/watch?v=y55rLsSNUiM

Hooks 不会取代您处理异步操作的方式,它们只是对您习惯做的一些事情的抽象,例如调用 componentDidMount 或处理 state

在您给出的示例中,您实际上并不需要自定义挂钩:

function App() {
  const [data, setData] = useState(null);
  useEffect(() => {
    const fetchData = async () => {
      const job = await import("./job.json");
      const collegues = await import("./collegues.json");
      const person = await import("./person.json");
      setData({
        job,
        collegues,
        person
      })
    };
    fetchData()
  }, []);

  return <div className="App">{JSON.stringify(data)}</div>;
}

也就是说,如果您提供一个实际的 redux-saga 或您拥有的 thunk 代码的示例,您想要重构,我们可以看到实现该目标的步骤。

编辑:

话虽这么说,如果你还想做这样的事情,你可以看看这个:

https://github.com/dai-shi/react-hooks-async

import React from 'react';

import { useFetch } from 'react-hooks-async/dist/use-async-task-fetch';

const UserInfo = ({ id }) => {
  const url = `https://reqres.in/api/users/${id}?delay=1`;
  const { pending, error, result, abort } = useFetch(url);
  if (pending) return <div>Loading...<button onClick={abort}>Abort</button></div>;
  if (error) return <div>Error:{error.name}{' '}{error.message}</div>;
  if (!result) return <div>No result</div>;
  return <div>First Name:{result.data.first_name}</div>;
};

const App = () => (
  <div>
    <UserInfo id={'1'} />
    <UserInfo id={'2'} />
  </div>
);

编辑

这是一个有趣的方法https://swr.now.sh/#dependent-fetching

这是现实生活中很常见的场景,你想等待第一次抓取完成,然后进行下一次抓取。

请查看新的codesandbox: https://codesandbox.io/s/p92ylrymkj

当你做获取请求时,我使用了生成器。数据以正确的顺序检索。点击 fetch data 按钮后,去控制台看看。

希望这就是您要找的。

我相信您遇到这个问题是因为获取挂钩的实现不佳,而且示例太基础了,我们无法理解。如果您将在同一组件中使用工作、同事和人员,您应该明确说明。如果是这样,最好将它们分开。

话虽这么说,让我给你举个我自己的 fetch hook 的例子:

const { loading, error, value } = useResource<Person>(getPerson, personId)

我有这样一个钩子,它有自己的加载状态、错误、值等。
它有两个参数:
- 获取方法
- 获取方法参数

有了这样的结构,你就可以把你的资源链在一起。
useResource 实现只是创建一个状态并在 useEffect 中检查 属性 是否发生变化等。如果发生变化,它会调用 fetch 方法。