首页 > 解决方案 > 在辅助函数中使用钩子

问题描述

我有如下功能

import React from "react";
import { useSelector, useDispatch } from "react-redux";

export const getCat = () => {
  const lang = useSelector((state) => state.main.language);
  return fetch("https://example.co/get/cat.php?lang="+lang, {
    method: "GET",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  })
    .then((response) => response.json())
    .then((responseData) => {
      return responseData;
    })
    .catch((error) => console.warn(error));
};

我想使用 useselector 访问状态值并将其传递给我的 url。但我收到以下错误

    Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

但我有其他类似下面的文件,它工作正常。

const Lang = () => {
  const lang = useSelector((state) => state.main.language);
  console.log("lang--" + lang);
};
export default Lang;

标签: reactjsreact-nativereact-redux

解决方案


你不能在辅助函数中使用钩子,因为 React 不在直接调用的辅助函数的范围内。请记住,仅导入 React 和钩子函数不会将 React 纳入范围。尽管 React 函数组件只是函数,但它们在 React 框架内被处理和调用,这与直接调用辅助函数不同,例如您将要执行的操作getCat()

要从您直接调用的辅助函数内部访问状态,您有几个选择:

将变量传递给代表您的状态的函数

const getCat = state => {
   const lang = state.main.language;
   ...
}

独立传递状态值

const getCat = lang => {
    ...
}

将函数委托传递给您的辅助函数,该函数能够从调用您的辅助函数的组件中访问状态

const getCat = stateFunc => {
    const lang = stateFunc();
    ...
}

如果您只需要读取状态,这一切都很好,但与任何状态变量一样,请注意您如何更改任何值。


推荐阅读