You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何拆分React组件中的单行箭头函数代码以添加断点?

问题:如何拆分React组件中的返回函数以便添加断点?

我有以下React组件:

const AuthInit: FC<WithChildren> = ({children}) => {
  const {auth, logout, setCurrentUser} = useAuth()
  const didRequest = useRef(false)
  const [showSplashScreen, setShowSplashScreen] = useState(true)
  // 渲染应用前,我们需要通过authToken(示例中为API_TOKEN)请求用户信息
  useEffect(() => {
    const requestUser = async (apiToken: string) => {
      try {
        if (!didRequest.current) {
          const {data} = await getUserByToken(apiToken)
          if (data) {
            setCurrentUser(data)
          }
        }
      } catch (error) {
        console.error(error)
        if (!didRequest.current) {
          logout()
        }
      } finally {
        setShowSplashScreen(false)
      }

      return () => (didRequest.current = true)
    }

    if (auth && auth.api_token) {
      requestUser(auth.api_token)
    } else {
      logout()
      setShowSplashScreen(false)
    }
    // eslint-disable-next-line
  }, [])

  return showSplashScreen ? <LayoutSplashScreen /> : <> {children} </>
}

其中这行代码:

return () => (didRequest.current = true)

需要拆分为多行,方便在didRequest.current = true处添加断点,具体做法如下:

解决方案

把单行箭头函数改成用大括号包裹的多行函数体,让赋值语句成为独立的一行,这样就能直接在目标行添加断点了:

return () => {
  didRequest.current = true;
};

说明

原来的写法是用圆括号包裹的单行表达式,调试器无法精准定位到赋值操作的位置;改成大括号包裹的语句块后,每一行代码都是独立的执行单元,调试时就能在didRequest.current = true这行正常添加断点。

内容的提问来源于stack exchange,提问作者PussInBoots

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:30:59