javascript - 如何在组件中使用 react useRef
问题描述
我正在尝试使用上下文来允许所有组件都可以使用身份验证状态。但是我被这个错误难住了
错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。这可能由于以下原因之一而发生:
- 你可能有不匹配的 React 版本和渲染器(例如 React DOM)
- 您可能违反了 Hooks 规则
- 您可能在同一个应用程序中拥有多个 React 副本有关如何调试和修复此问题的提示,请参阅https://reactjs.org/link/invalid-hook-call 。
src/utils/hooks.js:22
19 | // }, [pokemonName, run])
20 | const defaultInitialState = { status: "idle", data: null, error: null };
21 | function useAsync(initialState) {
> 22 | const initialStateRef = useRef({
23 | ...defaultInitialState,
24 | ...initialState
25 | });```
UseProvideAuth
src/components/helper/context.js:28
25 |
26 |
27 | function UseProvideAuth(props) {
> 28 | const {
29 | data: user,
30 | status,
31 | error,
handleSubmit
src/components/login/login-form/index.js:13
10 | function handleSubmit(event) {
11 | event.preventDefault();
12 | const { email, password } = event.target.elements;
> 13 | run(
| ^ 14 | onSubmit({
15 | email: email.value,
16 | password: password.value
Index.js
<React.StrictMode>
<ProvideAuth>
<App />
</ProvideAuth>
</React.StrictMode>,
ProvideAuth
function ProvideAuth({ children }) {
return (
<BrowserRouter>
<authContext.Provider value={UseProvideAuth}>{children}</authContext.Provider>
</BrowserRouter>
);
}
UseProvideAuth
function UseProvideAuth(props) {
const {
data: user,
status,
error,
isLoading,
isIdle,
isError,
isSuccess,
run,
setData
} = useAsync();
useAsync
const defaultInitialState = { status: "idle", data: null, error: null };
function useAsync(initialState) {
const initialStateRef = useRef({
...defaultInitialState,
...initialState
});
Here is a minimal setup on [codesandbox][1]
Any help would be appreciated.
[1]: https://codesandbox.io/s/frosty-silence-b0c8i
解决方案
推荐阅读
- matplotlib - PyQt4/matplotlib:如何修复 MatplotlibDeprecationWarning 由于 axes.hold()
- react-bootstrap - 对于 React-bootstrap 网格,如何在 Col 中使用 bsPrefix?
- flutter - Flutter:无法迁移到 AndroidX
- python - 来自`py.test`时有标准输出,但`python -m pytest`没有标准输出
- python - in Python3, how could I import a python file which is reading a xml comfig?
- azure-sql-database - SQL DW 将 [datetime2](7) 转换为 [bigint]
- android - 特殊符号未在 webview 中显示
- java - 无法在 java 中执行 SPARQL 查询(QueryExecution .execSelect() 方法中的异常)
- c++ - 在 C++ 中替代 bash 同步
- android - 启动应用程序时出现此错误