首页 > 解决方案 > 在类中反应 useEffect 定义

问题描述

我正在尝试在我的类中设置 useEffect 挂钩(用于监听路由更改),其定义如下 -

export default class AppManger extends Component{
    //constructor
    //componentWillMount
    //reneder
    //...
}

我的其余钩子已定义并按预期工作,但是当我尝试定义时useEffect-

useEffect(() => {
        const { pathname } = location;
        console.log('New path:', pathname);
    }, [location.pathname]);

我得到 - ./src/components/AppManger.js

  Line 30:  Parsing error: Unexpected token

  28 |         }
  29 |     }
> 30 |     useEffect(() => {
     |               ^
  31 |         const { pathname } = location;
  32 |         console.log('New path:', pathname);
  33 |     }, [location.pathname]);

在 React 组件中定义箭头函数是否正确?

谢谢你。

标签: reactjsarrow-functionsuse-effect

解决方案


不,我的朋友,你不能在类组件中使用钩子,要使用你必须将类组件转换为功能组件。像这样 :

import React from "react";

export default AppManger = () => {
    useEffect(() => {
        const { pathname } = location;
        console.log('New path:', pathname);
    }, [location.pathname]);
}

推荐阅读