React 17:"useEffect has missing dependencies" 具有 useMutation 函数

React 17: "useEffect has missing dependencies" with useMutation function

我正在学习反应查询,以下代码按预期工作,但我收到此警告消息:

React Hook useEffect has missing dependencies: 'code' and 'mutate'. Either include them or remove the dependency array.eslintreact-hooks/exhaustive-deps

但是,如果我在依赖项数组中添加 'code' 和 'mutate',则会出现无限循环。

import React, { useState, useEffect } from "react";
import { useMutation } from "react-query";
import * as api from "../api/api";

const getQuery = () => {
  const queryParams = new URLSearchParams(window.location.search);
  return queryParams.get("code");
};

const Authentication = () => {
  const [code] = useState(getQuery());

  useEffect(() => {
    if (code) {
      mutate.mutate(code);
    }
  }, []);

  const auth = async () => {
    window.location.href = `https://www.betaseries.com/authorize?client_id=${process.env.REACT_APP_API_KEY}&scope=&redirect_uri=${process.env.REACT_APP_API_URL_CALLBACK}`;
  };

  const mutate = useMutation(api.access_token, {
    onSuccess: (data) => {
      localStorage.setItem("isAuth", data.data.access_token);
    },
  });

  return <button onClick={auth}>Login</button>;
};

export default Authentication;

我做了什么的简短说明:

  1. 用户点击登录按钮,他被重定向到该网站以输入他的登录名/密码
const auth = async () => {
    window.location.href = `https://www.betaseries.com/authorize?client_id=${process.env.REACT_APP_API_KEY}&scope=&redirect_uri=${process.env.REACT_APP_API_URL_CALLBACK}`;
  };
  1. 成功登录后,他被重定向到我的网站,参数为 url ?code=xxx

  2. 我捕捉到代码并用它来调用一条路由,该路由将为我提供他的 access_token

  useEffect(() => {
    if (code) {
      mutate.mutate(code);
    }
  }, []);

mutate 函数本身是稳定的,但 useMutation 返回的对象不是。如果你破坏,你可以将它添加到你的依赖数组:

const { mutate } = useMutation(…)

您可以直接将 codemutate 传递给依赖数组,因为您的 useEffect 依赖于变量代码的变化和它自身的变异对象。以下是您可以尝试的方法:

useEffect(() => {
    if (code) {
      mutate.mutate(code);
    }
  }, [code, mutate]);