reactjs - 在类中反应 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]);
}
推荐阅读
- python - 问:Selenium NoSuchElementException(非显式等待或 iframe)
- user-interface - 如何在 Julia、WebIO 和 Blink 中使用 handle(w, “flag”)?
- c# - C# Entity Framework LINQ to Entities 在 SELECT 表达式下添加参数 WHERE 表达式
- python - 我不明白 django 的 path() 是如何工作的
- vue.js - 如何访问 vue.js 中的索引以获取循环元素?
- unity3d - Unity 2D Top-Down 鼠标面临武器旋转问题
- android - 在没有 xml 的情况下以编程方式创建 Listview:不显示任何单元格
- python - 如何在 output.csv 文件中包含“for”循环变量
- python - 超过指定数量。的列用 Pandas 重命名
- angular - Angular:在产品模式下点击刷新后 URL 发生变化