为了账号安全,请及时绑定邮箱和手机立即绑定

Hooks 规则顶级在哪里

Hooks 规则顶级在哪里

三国纷争 2021-12-02 19:41:18
我在 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();该应用程序不编译×无效的钩子调用。钩子只能在函数组件的主体内部调用。这可能是由于以下原因之一而发生的: 1. 你的 React 和渲染器的版本可能不匹配(例如 React DOM) 2. 你可能违反了 Hooks 规则 3. 你可能有多个 React 副本同一个应用程序解决了这个问题。现在,我试图理解规则,必须仅在组件的顶层调用钩子,以便 react 始终以相同的方式加载组件。但我的最高水平在哪里?我试图把渲染放在外面,作为组件的一个属性,我仍然有同样的加载错误。
查看完整描述

2 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

你打破了钩的规则,即:No Hooks in classes。


这应该是这里的诀窍。尝试将其重写为如下所示:


function Login(props: LoginProps) {

    const [data, setData] = useState({ email: '', password: '' });

    const { t } = useTranslation();


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


    render() {

        return <div>

            {/*...*/ }

        </div>

    }


}

在文档页面上,甚至还有一个页面只介绍 Hook Errors/Warnings: Invalid Hook Call Warning


在Breaking the Rules of Hooks 中,它指出:


🔴 不要在类组件中调用 Hook。

🔴 不要调用事件处理程序。

🔴 不要在传递给 useMemo、useReducer 或 useEffect 的函数中调用 Hook。


查看完整回答
反对 回复 2021-12-02
?
慕妹3242003

TA贡献1824条经验 获得超6个赞

钩子用在功能组件中,这里有一个类组件,这就是为什么它在这里抛出错误,错误就是说

钩子只能在函数组件的主体内部调用。

希望能帮助到你


查看完整回答
反对 回复 2021-12-02
  • 2 回答
  • 0 关注
  • 155 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信