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;




猜你喜欢

转载自blog.csdn.net/EcbJS/article/details/112768672
今日推荐