React 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 组件中定义箭头函数的正确方法吗?

谢谢。

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

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

useEffect 和所有其他钩子只能在功能组件中使用。 在类组件中,应使用生命周期方法。 以下是更多信息: 1( https://reactjs.org/docs/state-and-lifecycle.html - 生命周期方法 2( https://reactjs.org/docs/hooks-intro.html - 钩子

最新更新