无法在类组件 React.js 中使用 useState [英] Unable to use useState in class component React.js

查看:65
本文介绍了无法在类组件 React.js 中使用 useState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 react 中创建常量,如下所示:

const [firstFocus, setFirstFocus] = React.useState(false);const [lastFocus, setLastFocus] = React.useState(false);

代码中使用的常量如下:

import React, { Component } from 'react'从 'axios' 导入 axios进口 {按钮,卡片,卡头,卡体,卡片页脚,形式,输入,输入组插件,输入组文本,输入组,容器,上校来自反应带";类 PostForm 扩展组件 {构造函数(道具){超级(道具)this.state = {电子邮件: '',密码: ''}}changeHandler = (e) =>{this.setState({ [e.target.name]: e.target.value })}submitHandler = (e) =>{e.preventDefault()控制台日志(这个状态)axios.post('https://jsonplaceholder.typicode.com/posts', this.state).then(响应 => {控制台日志(响应)}).catch(错误=> {控制台日志(错误)})}使成为() {const { 电子邮件,密码 } = this.state**const [firstFocus, setFirstFocus] = React.useState(false);const [lastFocus, setLastFocus] = React.useState(false);**返回 (<div><Col className="ml-auto mr-auto" md="4"><Card className="card-login card-plain"><Form onSubmit={this.submitHandler} className="form"><CardHeader className="text-center"></卡片头><卡片体><输入组类名={无边框输入-lg"}><InputGroupAddon addonType="prepend"><InputGroupText><i className="now-ui-icons ui-1_email-85"></i></InputGroupText></InputGroupAddon><输入占位符=电子邮件"类型=文本"名称=电子邮件"值={电子邮件}onChange={this.changeHandler}//onFocus={() =>设置第一焦点(真)}//onBlur={() =>设置第一焦点(假)}></输入></输入组><输入组类名={无边界输入-lg"}><InputGroupAddon addonType="prepend"><InputGroupText><i className="now-ui-icons ui-1_lock-circle-open"></i></InputGroupText></InputGroupAddon><输入占位符=密码"类型=密码"名称=密码"值={密码}onChange={this.changeHandler}//onFocus={() =>setLastFocus(true)}//onBlur={() =>setLastFocus(false)}></输入></输入组></CardBody><CardFooter className="text-center"><按钮堵塞className="btn-round"颜色=信息"类型=提交"大小=lg">开始</按钮><div className="pull-right"><h6>e.preventDefault()}>需要帮忙?</a>

</CardFooter></表格></卡片></Col>

)}}导出默认 PostForm

但是,当我尝试这样做时,我收到以下错误:

<块引用>

无效的钩子调用.Hooks 只能在 a 的 body 内部调用功能组件.

我在那里为电子邮件和密码创建了另一个常量,它工作得很好,所以我不确定为什么我的 useState 常量不起作用.任何帮助或指导都非常感谢,因为我对反应很陌生.谢谢!

解决方案

在 React 中,我们有两种构建组件的方法:类和函数.

文档

<块引用>

Hook 是 React 16.8 中的新增功能.它们让您无需编写类即可使用状态和其他 React 功能.

使用状态钩子:

import React, { useState } from 'react';函数示例(){//声明一个新的状态变量,我们称之为count";const [count, setCount] = useState(0);返回 (<div><p>您点击了 {count} 次</p><button onClick={() =>setCount(count + 1)}>点击我

);}

等价类示例:

class Example extends React.Component {构造函数(道具){超级(道具);this.state = {计数:0};}使成为() {返回 (<div><p>您点击了 {this.state.count} 次</p><button onClick={() =>this.setState({ count: this.state.count + 1 })}>点击我

);}}

I am trying to create constants in react as follows:

const [firstFocus, setFirstFocus] = React.useState(false);
const [lastFocus, setLastFocus] = React.useState(false);

The constants are being used in the code as follows:

import React, { Component } from 'react'
import axios from 'axios'

import {
    Button,
    Card,
    CardHeader,
    CardBody,
    CardFooter,
    Form,
    Input,
    InputGroupAddon,
    InputGroupText,
    InputGroup,
    Container,
    Col
} from "reactstrap";

class PostForm extends Component {
    constructor(props) {
        super(props)

        this.state = {
            email: '',
            password: ''
        }
    }

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

    submitHandler = (e) => {
        e.preventDefault()
        console.log(this.state)
        axios.post('https://jsonplaceholder.typicode.com/posts', this.state)
            .then(response => {
                console.log(response)
            })
            .catch(error => {
                console.log(error)
            })
    }


    render() {
        const { email, password } = this.state
        **const [firstFocus, setFirstFocus] = React.useState(false);
        const [lastFocus, setLastFocus] = React.useState(false);**
        return (

            <div>
                <Col className="ml-auto mr-auto" md="4">
                    <Card className="card-login card-plain">
                        <Form onSubmit={this.submitHandler} className="form">
                            <CardHeader className="text-center">
                            </CardHeader>
                            <CardBody>
                                <InputGroup
                                    className={
                                        "no-border input-lg"
                                    }
                                >
                                    <InputGroupAddon addonType="prepend">
                                        <InputGroupText>
                                            <i className="now-ui-icons ui-1_email-85"></i>
                                        </InputGroupText>
                                    </InputGroupAddon>
                                    <Input
                                        placeholder="Email"
                                        type="text"
                                        name="email"
                                        value={email}
                                        onChange={this.changeHandler}
                                    // onFocus={() => setFirstFocus(true)}
                                    // onBlur={() => setFirstFocus(false)}
                                    ></Input>
                                </InputGroup>
                                <InputGroup
                                    className={
                                        "no-border input-lg"
                                    }
                                >
                                    <InputGroupAddon addonType="prepend">
                                        <InputGroupText>
                                            <i className="now-ui-icons ui-1_lock-circle-open"></i>
                                        </InputGroupText>
                                    </InputGroupAddon>
                                    <Input
                                        placeholder="Password"
                                        type="password"
                                        name="password"
                                        value={password}
                                        onChange={this.changeHandler}
                                    // onFocus={() => setLastFocus(true)}
                                    // onBlur={() => setLastFocus(false)}
                                    ></Input>
                                </InputGroup>
                            </CardBody>
                            <CardFooter className="text-center">
                                <Button
                                    block
                                    className="btn-round"
                                    color="info"
                                    type="submit"
                                    size="lg"
                                >
                                    Get Started
                    </Button>
                                <div className="pull-right">
                                    <h6>
                                        <a
                                            className="link"
                                            href="#pablo"
                                            onClick={e => e.preventDefault()}
                                        >
                                            Need Help?
                        </a>
                                    </h6>
                                </div>
                            </CardFooter>
                        </Form>
                    </Card>
                </Col>
            </div>
        )
    }
}

export default PostForm

However, when I try to do this I get the following error:

Invalid hook call. Hooks can only be called inside of the body of a function component.

I created another constant there for email and password and it worked just fine so I'm not sure why my useState constants aren't working. Any help or guidance is much appreciated as I am very new to react. Thanks!

解决方案

In react, we have 2 ways to build components: classes and functions.

DOCS

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

Using the State Hook:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Equivalent Class Example:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

这篇关于无法在类组件 React.js 中使用 useState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆