reactjs - 在辅助函数中使用钩子
问题描述
我有如下功能
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;
解决方案
你不能在辅助函数中使用钩子,因为 React 不在直接调用的辅助函数的范围内。请记住,仅导入 React 和钩子函数不会将 React 纳入范围。尽管 React 函数组件只是函数,但它们在 React 框架内被处理和调用,这与直接调用辅助函数不同,例如您将要执行的操作getCat()
。
要从您直接调用的辅助函数内部访问状态,您有几个选择:
将变量传递给代表您的状态的函数
const getCat = state => {
const lang = state.main.language;
...
}
独立传递状态值
const getCat = lang => {
...
}
将函数委托传递给您的辅助函数,该函数能够从调用您的辅助函数的组件中访问状态
const getCat = stateFunc => {
const lang = stateFunc();
...
}
如果您只需要读取状态,这一切都很好,但与任何状态变量一样,请注意您如何更改任何值。
推荐阅读
- windows - 使用新的身份验证方法扩展 Windows Hello
- c# - .Net 核心 Web 应用程序在 localhost 上工作但不在 IIS 服务器上运行
- mysql - #Query 以根据特定条件填充不同的结果。(挑战者查询)
- windows - 高级休息客户端 - 不显示响应
- c++ - for循环c ++的问题
- python - Python:CircularQueue 从队列的开始到结束打印项目
- android - 使用子 Swich 小部件隐藏/显示父小部件
- windows - 具有现代外观和感觉的 WIX 安装程序
- c# - 如何将指纹扫描存储在我的计算机上而不是扫描仪内部?
- html - HTML 的打印样式仅在第一页上看起来不错