Javascript 在上下文中调用React钩子

Javascript 在上下文中调用React钩子,javascript,reactjs,react-hooks,react-context,Javascript,Reactjs,React Hooks,React Context,我正在使用的是一个React管理控制台,它基于材质UI,并使用React上下文和钩子进行设计 项目为UserUserContext.js定义了一个上下文,代码很简单(): 我得到了一个错误: React Hook "useSWR" is called in function "loginUser" which is neither a React function component or a custom React Hook function react-hooks/rules-of-

我正在使用的是一个
React管理控制台
,它基于
材质UI
,并使用React
上下文
钩子
进行设计

项目为User
UserContext.js
定义了一个上下文,代码很简单():

我得到了一个错误:

React Hook "useSWR" is called in function "loginUser" which is neither a React 

function component or a custom React Hook function  react-hooks/rules-of-hooks
看来我不能把钱放在这里。但从逻辑上讲,这是它应该在的地方


如何使用
swr
或此处

您需要这样做:

function FetchOnClick() {
  const [shouldFetch, setShouldFetch] = React.useState(false);
  const { data } = useSWR(!shouldFetch ? null : "/api/users/1", fetcher);

  return (
    <>
      <button disable={shouldFetch} onClick={ () => setShouldFetch(true) }>Fetch</button>
      {data ? <h1>{data.fullName}</h1> : null}
    </>
  );
}
函数FetchOnClick(){ const[shouldFetch,setShouldFetch]=React.useState(false); const{data}=useSWR(!shouldFetch?null:“/api/users/1”,fetcher); 返回( setShouldFetch(true)}>Fetch {data?{data.fullName}:null} ); }
受@sergiodxa的代码启发:

您需要执行以下操作:

function FetchOnClick() {
  const [shouldFetch, setShouldFetch] = React.useState(false);
  const { data } = useSWR(!shouldFetch ? null : "/api/users/1", fetcher);

  return (
    <>
      <button disable={shouldFetch} onClick={ () => setShouldFetch(true) }>Fetch</button>
      {data ? <h1>{data.fullName}</h1> : null}
    </>
  );
}
函数FetchOnClick(){ const[shouldFetch,setShouldFetch]=React.useState(false); const{data}=useSWR(!shouldFetch?null:“/api/users/1”,fetcher); 返回( setShouldFetch(true)}>Fetch {data?{data.fullName}:null} ); }
受@sergiodxa的代码启发:

您的函数需要返回一个React元素才能将其视为组件…您的函数需要返回一个React元素才能将其视为组件。。。
function FetchOnClick() {
  const [shouldFetch, setShouldFetch] = React.useState(false);
  const { data } = useSWR(!shouldFetch ? null : "/api/users/1", fetcher);

  return (
    <>
      <button disable={shouldFetch} onClick={ () => setShouldFetch(true) }>Fetch</button>
      {data ? <h1>{data.fullName}</h1> : null}
    </>
  );
}