React-hooks-global-state 按下按钮时钩子调用无效
2022-10-24
405
我试图使用 react-hooks-global-state 在功能性反应中创建基于用户输入更新的全局钩子,但遇到了以下错误:
Uncaught Error: 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
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
首先,这里是我的 package.json 依赖项:
"dependencies": {
"@expo/webpack-config": "^0.17.0",
"bootstrap": "^5.2.2",
"expo": "~46.0.9",
"expo-status-bar": "~1.4.0",
"react": "^18.2.0",
"react-bootstrap": "^2.5.0",
"react-dom": "^18.2.0",
"react-hooks-global-state": "^2.0.0",
"react-native": "0.69.5",
"react-native-web": "~0.18.7"
},
这是一个简单的例子:
import { React } from 'react';
import { createGlobalState } from 'react-hooks-global-state';
import { Text } from 'react-native';
const initialState = { myVar: 1 };
const { useGlobalState } = createGlobalState(initialState);
export default function App() {
const [myVar, setMyVar] = useGlobalState('myVar');
setMyVar(10);
return (
<>
<Text>
{myVar}
</Text>
<button onClick={changeValue}>
Set to 0
</button>;
</>
);
}
function changeValue(){
const [myVar, setMyVar] = useGlobalState('myVar');
setMyVar(0);
}
具体来说,错误发生在
changeValue()
中的
const [myVar, setMyVar] = useGlobalState('myVar');
,因为它在按下按钮时被调用。但是,我可以确认,如果我删除动态用户输入(即直接在 App() 函数中调用 changeValue()),全局钩子就会起作用,所以我不确定为什么会遇到这个错误。
编辑 :这里有一个 changeValue() 函数非动态工作的示例:
import { React } from 'react';
import { createGlobalState } from 'react-hooks-global-state';
import { Text } from 'react-native';
const initialState = { myVar: 1 };
const { useGlobalState } = createGlobalState(initialState);
export default function Profile() {
const [myVar, setMyVar] = useGlobalState('myVar');
changeValue();
return (
<>
<Text>
{myVar}
</Text>
</>
);
}
function changeValue(){
const [myVar, setMyVar] = useGlobalState('myVar');
setMyVar(0);
}
1个回答
出现此错误是因为您调用了 React hooks
setMyVar
,而不是在 React Component 上
import { React } from 'react';
import { createGlobalState } from 'react-hooks-global-state';
import { Text } from 'react-native';
const initialState = { myVar: 1 };
const { useGlobalState } = createGlobalState(initialState);
export default function App() {
const [myVar, setMyVar] = useGlobalState('myVar');
function changeValue(){
setMyVar(0);
}
return (
<>
<Text>
{myVar}
</Text>
<button onClick={changeValue}>
Set to 0
</button>;
</>
);
}
edhi.uchiha
2022-10-25