React钩子全局状态在按下按钮时钩子调用无效



我正试图使用react hooks全局状态在基于用户输入更新的函数react中创建全局钩子,但遇到了以下错误:

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');,因为它是在按钮按下时调用的。然而,如果我删除动态用户输入(即直接在应用程序((函数中调用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);
}

错误是因为您调用的react hooksetMyVar不在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>;
</>
);
}

相关内容

  • 没有找到相关文章

最新更新