当前位置: 首页 > 知识库问答 >
问题:

不能在类组件中调用React挂钩“useContext”

吕俊美
2023-03-14

获取以下错误。请帮忙。第9:36行:不能在类组件中调用React钩子“useContext”。必须在React函数组件或自定义React钩子函数中调用React钩子。React钩子/钩子规则第9:47行:“AccountContext”未定义未定义未定义第126:37行:“switchToSignup”未定义未定义未定义

搜索关键字以了解有关每个错误的更多信息。

import React, { useContext } from "react";
import { BoldLink, BoxContainer, FormContainer, MutedLink, SubmitButton, Input } from "./common";
import { Marginer } from "../marginer";

  
export class LoginForm extends React.Component {
    constructor() {
        const { switchToSignup } = useContext(AccountContext);
    super();
    this.state = {
      input: {},
      errors: {}
    };
     
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
     
  handleChange(event) {
    let input = this.state.input;
    input[event.target.name] = event.target.value;
  
    this.setState({
      input
    });
  }
     
  handleSubmit(event) {
    event.preventDefault();
  
    if(this.validate()){
        console.log(this.state);
  
        let input = {};
        input["email"] = "";
        input["password"] = "";
        this.setState({input:input});
  
        alert('Demo Form is submitted');
    }
  }
  
  validate(){
      let input = this.state.input;
      let errors = {};
      let isValid = true;
   
     
  
      if (!input["email"]) {
        isValid = false;
        errors["email"] = "Please enter your email Address.";
      }
  
      if (typeof input["email"] !== "undefined") {
          
        var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        if (!pattern.test(input["email"])) {
          isValid = false;
          errors["email"] = "Please enter valid email address.";
        }
      }
  
      if (!input["password"]) {
        isValid = false;
        errors["password"] = "Please enter your password.";
      }
  
  
      if (typeof input["password"] !== "undefined") {
        if(input["password"].length < 6){
            isValid = false;
            errors["password"] = "Please add at least 6 charachter.";
        }
      }
  
  
      this.setState({
        errors: errors
      });
  
      return isValid;
  }
     
  render() {
    return (
            <div>
            <form onSubmit={this.handleSubmit}>
            <BoxContainer>
            <FormContainer>
            <div class="form-group">
            <Input 
            type="text" 
            name="email" 
            value={this.state.input.email}
            onChange={this.handleChange}
            class="form-control" 
            placeholder="Enter email" 
            id="email" />

            <div className="text-danger">{this.state.errors.email}</div>
            </div>

            <div class="form-group">
            <Input 
            type="password" 
            name="password" 
            value={this.state.input.password}
            onChange={this.handleChange}
            class="form-control" 
            placeholder="Enter password" 
            id="password" />

            <div className="text-danger">{this.state.errors.password}</div>
            </div>

            </FormContainer>
            <Marginer direction="vertical" margin={10} />
      <MutedLink href="#">Forget your password?</MutedLink>
      <Marginer direction="vertical" margin="1.6em" />
      <SubmitButton type="submit">Signin</SubmitButton>
      <Marginer direction="vertical" margin="1em" />
      <MutedLink href="#">
        Don't have an accoun?{" "}
        <BoldLink href="#" onClick={switchToSignup}>
          Signup
        </BoldLink>
      </MutedLink>
            </BoxContainer>
            </form>
            </div>
    );
  }
}

共有1个答案

吴浩博
2023-03-14

正如错误消息所述,您不能混合使用钩子和类组件。您需要切换LoginForm作为函数组件,或者使用AccountContext。消费者直接购买,例如:

render() {
  return (
    <AccountContext.Consumer>
      (({ switchToSignup }) => (
        <div>
          // do something with switchToSignup
        </div>
      ))
    </AccountContext.Consumer>
  );
}

您似乎还忘记导入AccountContext。您还需要确保AccountContext。提供商安装在应用程序树中此组件上方的某个位置。要阅读有关React上下文的更多信息,请查看文档。

 类似资料:
  • 得到以下错误。请帮帮这个。第9:36行:React钩子“useContext”不能在类组件中调用。React钩子必须在React函数组件或自定义React钩子函数react-hooks/rules-of-hooks第9:47行:“AccountContext”未定义no-undef第126:37行:“switch tosignup”未定义no-undef

  • 我是反应的初学者。我试图将我的数据库的值从一个文件发送到另一个使用反应挂钩,并得到以下错误有人能帮我吗? 第5:41行:不能在顶层调用React钩子“useState”。必须在React函数组件或自定义React钩子函数React钩子/钩子规则代码中调用React钩子:

  • 问题内容: 我是React的新手,现在我想在表中显示一些记录,现在出现此错误。请帮帮我。 无效的挂接调用。挂钩只能在功能组件的主体内部调用。发生这种情况可能是由于以下原因之一:1.您的React和渲染器版本可能不匹配(例如React DOM)2.您可能违反了《胡克规则》 3.您可能在其中包含多个React版本相同的应用程序请参阅有关如何调试和解决此问题的提示。 问题答案: 因为你。在此处查看更多信

  • 我在使用hook时遇到此错误。我有它的基本形式,查看react文档作为参考,但仍然得到这个错误。我已经准备好面对掌心时刻。。。

  • 如何使用钩子(或任何其他钩子)来复制? 在传统的类组件中,我将执行以下操作: 使用hook: (完整示例:https://codesandbox.io/s/2oo7zqzx1n) 这不起作用,因为在中返回的“cleanup”函数捕获装载期间的道具,而不是卸载期间的道具状态。 如何在不运行函数体(或清除)的情况下对每个道具更改进行清理? 一个类似的问题并没有涉及获得最新道具的部分。 文件状态为: 如

  • 摘要 在Mongoose中有一个post findOneAndUpdate钩子,在这个钩子里面我需要查询数据库。我正试图在另一个模型上执行。find(),但是每次我都得到以下错误: 误差