React类组件中使用useEffect报Unexpected token错误求助
React中类组件使用useEffect导致"Unexpected token"错误的解决方案
没错,就是你猜测的原因——React钩子(包括useEffect)只能在函数式组件或自定义钩子内部使用,类组件完全不支持钩子函数,这是React的硬性规则。
你在类组件的类体里直接写useEffect(() => { ... }),不仅违反了Hook的使用规则,还不符合JavaScript类的语法要求:类的主体只能定义方法、类属性,不能直接执行函数调用,这就是触发"Unexpected token"错误的直接原因。
下面给你两种可行的解决方案:
方案一:转成函数式组件使用useEffect
把类组件改成函数式组件,就能正常使用useEffect了,修改后的完整代码如下:
import React, { useState, useEffect } from 'react' function Effect() { const [count, setCount] = useState(0) // 模拟类组件的componentDidMount + componentDidUpdate useEffect(() => { console.log('Effect'); // 如果只想在组件挂载时执行一次,加上空依赖数组:[] // useEffect(() => { console.log('Effect'); }, []) }, [count]) // 依赖count变化时触发 const CH = () => { setCount(prevCount => prevCount + 1) } return( <> <button onClick={CH}>点击</button> <p>You have clicked me {count} times.</p> </> ) } export default Effect
方案二:在类组件中使用生命周期方法
如果不想改成函数式组件,可以用类组件的生命周期方法替代useEffect的功能,比如componentDidMount(组件挂载时执行)和componentDidUpdate(组件更新时执行):
import React, { Component } from 'react' class Effect extends Component { constructor() { super() this.state = { count: 0 } this.CH = () => { this.setState(prevState => { console.log(prevState); return { count: prevState.count + 1 } }) } } // 组件挂载后执行,对应useEffect加空依赖数组的场景 componentDidMount() { console.log('Effect: 组件挂载完成'); } // 组件更新后执行,对应useEffect依赖count的场景 componentDidUpdate(prevProps, prevState) { if (prevState.count !== this.state.count) { console.log('Effect: count更新了'); } } render() { return( <> <button onClick={this.CH}>点击</button> <p>You have clicked me {this.state.count} times.</p> </> ) } } export default Effect
内容的提问来源于stack exchange,提问作者CodeLect
相关产品推荐
相关产品推荐

