SWR 钩子错误:“未提供‘Fetcher’的参数”

问题描述

这是我第一次使用 SWR hook,实际上一切都很好。但是我有一个错误,我真的不知道那里发生了什么,所以让我先向您展示我的代码

这是全局配置

<AuthContext>
    {isValidRoute && <Navbar />}
    <SWRConfig
        value={{
          fetcher: (url: string) => axios.get(url).then(res => res.data)
        }}
    >
        <Component {...pageProps} />
    </SWRConfig>
</AuthContext>

这就是我使用它的地方

import useSWR from "swr";

import { NavbarPart3 } from "../NavbarStyled";
import { dataObject } from "../../../GlobalInterfaces/AuthContextInterfaces";

const Part3 = () => {
  if (typeof window !== "undefined") {
    const userId: dataObject = JSON.parse(localStorage.getItem("Auth"));
    const { data } = useSWR(
      "http://localhost:5000/api/user/singleU/" + userId.user.id
    );
    console.log(data);
  }

  return <NavbarPart3></NavbarPart3>;
};

export default Part3;

现在,这是错误

Expected 4 arguments,but got 1.ts(2554)
use-swr.d.ts(4,91): An argument for 'Fetcher' was not provided

目标:我只是想摆脱那个问题。您知道是什么原因导致了这个问题吗?

解决方法

我假设您在 Part3 组件中的某处调用了 NavBar 组件,这可以解释您所看到的错误。

SWRConfig 需要包装调用 Part3 的组件。尝试在 {isValidRoute && <Navbar />} 包装器内移动 SWRConfig

<AuthContext>
    <SWRConfig
        value={{
            fetcher: (url: string) => axios.get(url).then(res => res.data)
        }}
    >
        {isValidRoute && <Navbar />}
        <Component {...pageProps} />
    </SWRConfig>
</AuthContext>

作为旁注,do not conditionally call useSWR(这是一个自定义 React 钩子)在您的 Part3 组件中。将 useSWR 调用移至组件的顶层,并将 localStorage 调用移至 useEffect 内。

const Part3 = () => {
    const [userId,setUserId] = useState()
    const { data } = useSWR(
        // Using the arrow function syntax so that the request is only made when `userId.user.id` is valid
        () => "http://localhost:5000/api/user/singleU/" + userId.user.id
    );

    useEffect(() => {
        const auth = JSON.parse(localStorage.getItem("Auth"));
        setUserId(auth);
    },[]);

    console.log(data);

    return <NavbarPart3></NavbarPart3>;
};

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...