组件销毁后撤消 API 调用

Undo API call after component destroy

我 API 使用 useEffect 调用组件挂载并根据响应做一些状态更改,但是如果我的组件在请求处于挂起状态时销毁怎么办,我该如何撤消此请求和所有函数尝试在成功时更改我的状态

所以使用 fetch 你可以这样做,如下所示,你可以在 js 中使用 native abort

您可以在 here

上阅读更多内容
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route, Switch, Link } from "react-router-dom";

import "./styles.css";

const Home = () => {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState(null);

  useEffect(() => {
    const abortController = new AbortController();

    const getData = async () => {
      try {
        setIsLoading(true);
        const response = await fetch(
          "https://jsonplaceholder.typicode.com/comments",
          {
            method: "get",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json"
            },
            signal: abortController.signal
          }
        );

        if (response.ok) {
          const body = await response.json();
          setData(body);
          setIsLoading(false);
          return;
        }
        const customError = {
          message: "Some Error Occured"
        };
        throw customError;
      } catch (error) {
        console.log(error.name);
        setIsLoading(false);
        if (error.name === "AbortError") {
          setErrorMessage("Request has aborted");
          return;
        }
        setErrorMessage("Internal server error");
      }
    };

    getData();
    return () => {
      abortController.abort();
    };
  }, []);

  return (
    <>
      {isLoading && <span>Loading Data, Please wait...</span>}
      {errorMessage && <span>{errorMessage}</span>}
      {data.length > 0
        ? data.map(d => {
            return <p key={d.id}>{d.name}</p>;
          })
        : null}
    </>
  );
};

const Products = () => <>Products</>;

function App() {
  return (
    <BrowserRouter>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/products">Products</Link>
        </li>
      </ul>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/products" component={Products} />
      </Switch>
    </BrowserRouter>
  );
}

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

工作codesandbox

注意:您需要打开开发工具并将网络选项卡节流到从网上减慢 3g 并打开控制台,这样当单击产品 link 时,api 将被取消。

我希望这能更好地看待这个问题

编码愉快 :)