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

ReactJS如何正确更新数据?替换componentWillMount后页面数据不刷新

问题排查与修复方案

问题原因

  • 核心错误:你将this.loadingData赋值为首次fetch请求返回的Promise实例,定时器setInterval每次执行时只是引用这个已经完成的旧Promise,根本不会重新发起网络请求、也不会触发新的setState更新,因此页面不会同步刷新。
  • 附加错误:组件卸载时仅将this.timer赋值为null,没有调用clearInterval清除定时器,会导致内存泄漏,定时器会在组件销毁后继续运行。
  • 补充说明:你最初的旧版本代码本身也存在不规范问题:直接在定时器中调用componentWillMount()不符合生命周期方法的使用规范,只是刚好因为每次调用都重新执行了fetch逻辑所以碰巧能运行。

修复后代码

class Main extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      lang: 'ru'
    }
  }

  // 封装独立的请求方法
  fetchData = () => {
    fetch('file.json')
      .then(response => response.json())
      .then(result =>
        this.setState({
          data: result.data
        })
      );
  }

  componentDidMount() {
    // 组件挂载后先请求一次
    this.fetchData();
    // 定时器每次调用新的请求方法
    this.timer = setInterval(() => this.fetchData(), 5000);
  }

  componentWillUnmount() {
    // 正确清除定时器
    clearInterval(this.timer);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:09:03