【问题标题】:React useEffect definition in class在类中反应 useEffect 定义
【发布时间】:2020-09-06 15:39:09
【问题描述】:

我正在尝试在我的类中设置 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 组件中定义箭头函数的方式正确吗?

谢谢。

【问题讨论】:

  • 你不能在类组件中使用 useEffect(或任何钩子)
  • 但是我在我的类组件中使用了 componentWillMount。我需要监听路由变化。
  • 那不是钩子,是类组件生命周期函数
  • 放入类中,检查是否导入react

标签: reactjs arrow-functions use-effect


【解决方案1】:

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

import React from "react";

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

【讨论】:

【解决方案2】:

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

【讨论】:

  • 当路由发生变化时,哪个生命周期方法会通知?
  • 听起来你可能需要问一个新问题
猜你喜欢
  • 2020-10-19
  • 1970-01-01
  • 2020-07-08
  • 2021-09-30
  • 2020-11-05
  • 2023-03-22
  • 1970-01-01
  • 2019-08-21
  • 2021-07-20
相关资源
最近更新 更多