我有如下的函数
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;
不能在helper函数中使用钩子,因为React不在直接调用的helper函数的作用域中。请记住,仅仅导入React和钩子函数并不能将React纳入范围。尽管React函数组件只是从React框架中处理和调用的函数,但这与直接调用助手函数(如getCat()
(不同。
要从您直接调用的助手函数内部访问状态,您有几个选择:
将变量传递给表示您的状态的函数
const getCat = state => {
const lang = state.main.language;
...
}
通过独立中的状态值
const getCat = lang => {
...
}
将函数委托传递给辅助函数,该函数能够从调用辅助函数的组件中访问状态
const getCat = stateFunc => {
const lang = stateFunc();
...
}
如果您只需要读取状态,这是很好的,但和任何状态变量一样,要小心如何更改任何值。