gpt4 book ai didi

javascript - Hook的规则 顶层在哪里

转载 作者:行者123 更新时间:2023-11-28 16:58:00 24 4
gpt4 key购买 nike

我在 React 中有以下组件

import React from 'react'
import { Row, Col, Form, Input, Button, Card } from 'antd';
import { FormComponentProps } from 'antd/lib/form/Form';
import Particles from 'react-particles-js';
import { useTranslation } from "react-i18next";
import { connect } from 'react-redux';

import { RootState } from '../../services/store/rootReducer';
import { UsersActions } from '../../services/store';

interface LoginProps extends FormComponentProps {
rootState: RootState
}

class Login extends React.Component<LoginProps> {
state = { email: '', password: ''};

changeHandler = (e: any, name: any) => {
var value = e.target.value;
this.setState({[name]: value})
}

loginUser = () => {
try {
UsersActions.loginRequestAsync(this.state, (token: any) => {
console.log(token);
});
} catch(exception)
{
console.log(exception)
}
}

render() {
const { t } = useTranslation();
const { getFieldDecorator } = this.props.form;
return (
<div>
///blabla
</div>
)
}
}

const mapStateToProps = (state: RootState) => ({
rootState: state
});
const mapDispatchToProps = {}
const createdForm = Form.create()(Login);

export default connect(
mapStateToProps,
mapDispatchToProps
)(createdForm);

当我添加行

const { t } = useTranslation();

该应用程序无法使用

进行编译

×

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 fix this problem.

现在,我试图理解规则,必须仅在组件的顶层调用钩子(Hook),以便 react 始终以相同的方式加载组件。但我的顶层在哪里?

我尝试将其放在渲染之外并作为组件的属性,但仍然遇到相同的加载错误。

最佳答案

你违反了 Hooks 的规则,即:类中没有 Hooks

这确实应该是这里的技巧。尝试将其重写为如下内容:

function Login(props: LoginProps) {
const [data, setData] = useState({ email: '', password: '' });
const { t } = useTranslation();

const loginUser = () => { /* ... */ };

render() {
return <div>
{/*...*/ }
</div>
}

}

在文档页面上,甚至有一个页面只涉及 Hook 错误/警告:Invalid Hook Call Warning

Breaking the Rules of Hooks它指出:

  • 🔴 Do not call Hooks in class components.
  • 🔴 Do not call in event handlers.
  • 🔴 Do not call Hooks inside functions passed to useMemo, useReducer, or useEffect.

关于javascript - Hook的规则 顶层在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58552306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com