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

React函数组件挂载时,函数声明内部代码为何未自动执行?

问题

在以下React代码中,组件挂载时函数声明内部的代码并未运行。原本认为在将函数体赋值给fun变量的过程中,会执行console.log("hello inside declaration")并将变量i赋值为5,但实际并非如此。

import { useEffect } from "react";
export default function App() {

  let i = 0

  let fun = () => {
    i = 5;
    console.log("hello inside declaration")
    return i;
  }
  
  useEffect(() => {
    console.log("hello inside use effect");
  });
  
  console.log("hello after");
  
  return (
    <div className="App">
      <h2>{i}</h2>
    </div>
  );
}

控制台输出结果:

hello after 
hello inside use effect 

已知调用该函数会打印对应内容,但不解为何不调用时不会自动执行。

回答

这是JavaScript函数的基础特性,和React无关:

  • 你这里用的是箭头函数表达式:let fun = () => { ... },这一步只是定义了一个函数,并把这个函数的引用赋值给fun变量,函数内部的代码只会在你主动调用它(比如fun())的时候才会执行。
  • 组件渲染时,会依次执行let i=0、定义fun函数、执行console.log("hello after")、返回JSX,之后触发useEffect里的回调。整个过程中你只是定义了fun但从未调用,所以内部的console.log和i=5都不会执行。

如果要让函数内部代码执行,你需要在合适的时机调用它,比如在组件渲染时直接调用:

let fun = () => {
  i = 5;
  console.log("hello inside declaration")
  return i;
}
// 调用函数
fun();

或者在useEffect里调用,根据你的业务需求选择时机。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:12:08