如何执行内部包含React钩子的函数

时间:2020-06-22 06:05:20

标签: reactjs react-hooks auth0

我正在使用react和nodeJS构建一个应用程序。我想进行API调用,并在此函数内使用react钩子从Auth0获取令牌以对API进行身份验证。

async function CallApi(userId) {
  const { getTokenSilently } = useAuth0();
  const token = await getTokenSilently();
  try {
    const response = await fetch(process.env.API_URL + "users", {
      headers: {
        Authorization: `Bearer ${token}`,
        user_id: userId
      }
    });

    var result = JSON.stringify(await response.json());

  } catch (error) {
    console.error(error);
  }
  return result;
};

export default CallApi;

现在我想在另一个文件中调用此函数:

async componentDidMount() {
    this.setState({ readError: null });
    try {
      var profile = await CallApi("own");
      this.setState({
        username: profile.username,
        email: profile.email
      })
    } catch (error) {
      this.setState({ readError: error.message });
    }
  }

现在,如果我要打开此站点,则会收到错误Unhandled Rejection (Error): Invalid hook call. Hooks can only be called inside of the body of a function component.

我做错了什么,如何才能从该挂钩中获取令牌?

2 个答案:

答案 0 :(得分:1)

由于使用钩子调用useAuth0 ==>,因此您需要在功能组件或具有前缀use ==>的客户钩子中调用它{{ 1}}不是一个钩子==>您得到了错误。

  1. 创建CallApi钩子。

useCallApi

  • 现在我想在另一个文件中调用此函数,但是您需要 将您现有的组件转换为功能组件并使用 function useCallApi(userId) { const [result, setResult] = c() const { getTokenSilently } = useAuth0(); const [loading, setLoading] = useState(false) const [error, setError] = useState(null) const fetchResult = useCallback( async(userId) =>{ const token = await getTokenSilently(); try { setLoading(true) const response = await fetch(process.env.API_URL + "users", { headers: { Authorization: `Bearer ${token}`, user_id: userId } }); setLoading(false) var result = JSON.stringify(await response.json()); setResult(result) } catch (error) { setLoading(false) setError(error) console.error(error); } },[userId]) useEffect(() =>{ if(userId){ fetchResult() } },[userId]) return {userInfor: result, loading, error,fetchResult}; }; export default useCallApi;钩子。

  • 如果在声明useCallApi时传递字符串,例如useCallAPi(“ own”),它将直接调用api。

  • 您也可以useCallAPi并在要获取结果的任何地方调用const {result, fetchResult} = useCallAPi("own")

fetchResult("own")

已更新:如果要在功能组件的//other import import {useCallAPi} from "path_to/useCallApi.js" // you need to convert your class compoenent to this compoenent function AFunctionalComponent(userId) { const [readError, setReadError] = useState(null) // result include username and email walready const {result} = useCallAPi("own") return( // your ui render herer ) };上设置本地状态,则可以尝试

result

答案 1 :(得分:0)

https://reactjs.org/warnings/invalid-hook-call-warning.html

为避免混淆,在其他情况下不支持调用Hooks:

?不要在类组件中调用Hook。

?不要调用事件处理程序。

?不要在传递给useMemo,useReducer或useEffect的函数中调用Hooks。