类中的useEffect定义

问题描述 投票:0回答:1

我正在尝试在我的类中设置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组件中定义箭头功能是否正确?

谢谢。

reactjs arrow-functions use-effect
1个回答
0
投票
[不,我的朋友,您不能在类组件内部使用钩子,要使用它,必须将类组件转换为功能组件。像这样:

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


0
投票
useEffect和所有其他挂钩只能在功能组件中使用。在类组件中,应使用生命周期方法。这是更多信息:1)https://reactjs.org/docs/state-and-lifecycle.html-生命周期方法2)https://reactjs.org/docs/hooks-intro.html-挂钩
© www.soinside.com 2019 - 2024. All rights reserved.