.jsx中怎样使用useXXX等钩子呢?

来源:3-1 React简介和基础知识回顾

迷你侠

2021-03-25

我不太会在 .jsx 文件中使用useState等useXxx这些钩子函数,总是报错,怎么办?

import React,{useState,useEffect,Component} from "react";

class Home extends Component{
  constructor(props,context) {
	  //好像是这里报错了:
	  //好像是这里报错了:
	  //好像是这里报错了:
    const [name,setName] = useState("Mile"); 
    super(props,context);
  }
  render(){
    return(
      <div>
        <h1>首页</h1>
      </div>
    )
  }
}
export default Home;

报错信息:

index.js:1 src\page\home\index.jsx Line 5:28: React Hook “useState” cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks Search for the keywords to learn more about each error.

写回答

1回答

张轩

2021-03-25

同学你好欧 useState 这类的钩子函数只能在 function component(函数式组件)内使用,旧的 class component(类组件) 是不能使用 React Hooks的

0
0

React18+TS高仿AntD从零到一打造组件库

设计,开发,测试,发布再到 CI/CD,从0到1造轮子

2128 学习 · 959 问题

查看课程