我有如下功能
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;
答案 0 :(得分:1)
您不能在辅助函数中使用钩子,因为 React 不在直接调用的辅助函数的作用域内。请记住,仅导入 React 和钩子函数不会将 React 引入作用域。尽管 React 函数组件只是在 React 框架内处理和调用它们的函数,这与直接调用辅助函数(例如您将为 getCat()
执行的操作)不同。
要从直接调用的辅助函数内部访问状态,您有几个选择:
将变量传递给表示您的状态的函数
const getCat = state => {
const lang = state.main.language;
...
}
独立传递状态值
const getCat = lang => {
...
}
将函数委托传递给您的辅助函数,该函数可以从调用您的辅助函数的组件中访问状态
const getCat = stateFunc => {
const lang = stateFunc();
...
}
如果您只需要读取状态,这一切都很好,但与任何状态变量一样,请谨慎更改任何值。