簡體   English   中英

無法在 class 組件中調用 React Hook “useContext”

[英]React Hook “useContext” cannot be called in a class component

得到以下錯誤。 請幫助解決這個問題。 第 9:36 行:無法在 class 組件中調用 React Hook “useContext”。 必須在 React function 組件或自定義 React Hook function react-hooks/rules-of-hooks Line 9:47: 'AccountContext' is not defined no-undef Line 126:37 中調用 React Hooks:無非定義

搜索關鍵字以了解有關每個錯誤的更多信息。

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>
    );
  }
}

如錯誤消息所述,您不能混合使用掛鈎和 class 組件。 您要么需要將LoginForm切換為 function 組件,要么直接使用AccountContext.Consumer ,例如:

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

看起來您也忘記了導入AccountContext 您還需要確保AccountContext.Provider安裝在應用程序樹中此組件上方的某個位置。 要閱讀有關 React Context 的更多信息,請查看文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM