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

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.This could happen for one of the following reasons:

1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.

报错原因

  具体报错如上,错误原因是,没有把 hook 当做一个 Function Component ,而是当做了 Function 进行调用。下面是调用过程:

import React, { Component, Fragment } from 'react';
import { Example } from './Example.js'; //引入 hook 组件

class App extends Component {
	render() {
		return (
			<Fragment>
				<div>some thing...</div>
				{
					Example()  //执行
				}
			</Fragment>
		);
	}
}

export default App;

   hook 组件部分如下:

import React, { useState } from 'react';

export function Example() {
	 const [num, updateNum] = useState(0)
	 return <p onClick={() =>updateNum(num => num + 1)}>{num}</p>
}

解决方法

  正确的调用方式应该是组件式的调用:

import React, { Component, Fragment } from 'react';
import { Example } from './Example.js';

class App extends Component {
	render() {
		return (
			<Fragment>
				<div>some thing...</div>
				<Example />//写成一个组件,而不是执行函数
			</Fragment>
		);
	}
}

export default App;




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值