【发布时间】:2021-05-05 00:53:19
【问题描述】:
这里是非常新的 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.
我已多次阅读链接的故障排除页面,并尝试修复所有三个可能的原因,但均未成功。
- 我在我的
devDependencies中使用react17.0.1 和react-dom17.0.1。 - 我已经安装了
eslint-plugin-react-hooks规则来识别我是否在我的功能组件中没有正确使用钩子。 - 我已使用
npm ls react和npm ls react-dom确认我没有重复的 react 版本。
LoginForm.jsx
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
const $ = require('jquery');
const LoginForm = ({ onToken }) => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const submit = (event) => {
// DO NOT POST PARAMS
event.preventDefault();
// AJAX username and password
const loginData = {
username: username,
password: password
};
const options = {
url: 'api/login',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(loginData),
success: (data) => {
console.log(data);
onToken(data.token);
}
};
$.ajax(options);
console.log('Submitted!');
};
return (
<form onSubmit={submit}>
<label htmlFor="username">Username:</label><br/>
<input value={username} onChange={e => setUsername(e.target.value)} type="text" id="username" name="username"/><br/>
<label htmlFor="password">Password:</label><br/>
<input value={password} onChange={e => setPassword(e.target.value)} type="password" id="password" name="password"/><br/>
<input type="submit" value="Login"/>
</form>
);
};
LoginForm.propTypes = {
onToken: PropTypes.func
};
export default LoginForm;
我在我的项目的存储库上创建了一个分支,以便您查看任何其他信息:
分公司:https://github.com/GibsDev/node-password-manager/tree/login-conversion
提交:https://github.com/GibsDev/node-password-manager/commit/e0714b16bdbbf339fabf1aa4f6eefacd6d053427
【问题讨论】:
-
出现这个错误的地方,看来你的组件没问题。
-
发生在浏览器中。当我尝试查看包含此组件的页面时。也许我没有正确添加组件? github.com/GibsDev/node-password-manager/blob/login-conversion/…
标签: reactjs npm eslint react-dom