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

React类组件中setTimeout获取错误props值问题求助

React类组件中setTimeout延迟执行时无法获取点击时props的问题

问题原因

核心问题在于类组件中this.props的引用特性:

  • 类组件的this.props是React维护的可变引用,每当父组件更新(比如App切换用户),React会更新这个引用指向新的props对象。
  • 点击Follow按钮时,setTimeout会在6秒后触发showMessage,但此时this.props.user已经是父组件更新后的新值,而非点击瞬间的快照。
  • 箭头函数showMessage捕获的是组件实例的this,执行时会读取当前最新的this.props,自然拿不到点击时的旧值。

解决方案

方法1:点击时捕获props快照(推荐)

在handleClick中用闭包保存点击瞬间的user值,确保setTimeout执行时读取的是当时的快照:

class ProfilePageClass extends React.Component {
  handleClick = () => {
    // 捕获点击时的user props值
    const clickedUser = this.props.user;
    setTimeout(() => {
      alert('Followed ' + clickedUser);
    }, 6000);
  };

  render() {
    return <button onClick={this.handleClick}>Follow</button>;
  }
}

方法2:给showMessage传递参数

如果需要保留独立的showMessage方法,可在点击时把当前user作为参数传入:

class ProfilePageClass extends React.Component {
  showMessage = (user) => {
    alert('Followed ' + user);
  };

  handleClick = () => {
    const clickedUser = this.props.user;
    setTimeout(() => this.showMessage(clickedUser), 6000);
  };

  render() {
    return <button onClick={this.handleClick}>Follow</button>;
  }
}

完整代码示例

App组件

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      user: 'Dan',
    };
  }
  render() {
    return (
      <React.Fragment>
        <label>
          <b>Choose profile to view: </b>
          <select
            value={this.state.user}
            onChange={e => this.setState({ user: e.target.value })}
          >
            <option value="Dan">Dan</option>
            <option value="Sophie">Sophie</option>
            <option value="Sunil">Sunil</option>
          </select>
        </label>
        <h1>Welcome to {this.state.user}’s profile!</h1>
        <p>
          <ProfilePageClass user={this.state.user} />
          <b> (class)</b>
        </p>
      </React.Fragment>
    )
  }
}

修改后的ProfilePageClass组件

class ProfilePageClass extends React.Component {
  handleClick = () => {
    const clickedUser = this.props.user;
    setTimeout(() => {
      alert('Followed ' + clickedUser);
    }, 6000);
  };

  render() {
    return <button onClick={this.handleClick}>Follow</button>;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 17:25:19