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

React.js中作为Props传递的setCategory函数被持续调用问题排查

问题原因

在JSX的onClick属性中,你直接调用了this.setCategory("xxx"),这会导致组件渲染时就立即执行该函数,而非点击时触发。所有分类项的setCategory会在Navbar渲染阶段依次执行,最后执行的setCategory("general")覆盖了之前的状态,所以你会看到最后一个分类的事件被"持续触发"(实际是渲染时执行),同时点击分类项没有反应——因为onClick绑定的是函数执行后的返回值(undefined),不是可触发的函数引用。

另外,setState是异步操作,你在setCategory里直接console.log(this.state.category),打印的是更新前的旧值,无法看到最新状态。

解决办法
  1. 修正onClick绑定方式:给每个分类项的onClick传递一个箭头函数,包裹setCategory调用,确保只有点击时才执行:
// Navbar组件中dropdown-menu部分修改为:
<div className="dropdown-menu">
  <p className="dropdown-item cursor-pointer" onClick={() => this.setCategory("business")}>Business</p>
  <p className="dropdown-item cursor-pointer" onClick={() => this.setCategory("science")}>Science</p>
  <p className="dropdown-item cursor-pointer" onClick={() => this.setCategory("technology")}>Technology</p>
  <p className="dropdown-item cursor-pointer" onClick={() => this.setCategory("entertainment")}>Entertainment</p>
  <p className="dropdown-item cursor-pointer" onClick={() => this.setCategory("health")}>Health</p>
  <p className="dropdown-item cursor-pointer" onClick={() => this.setCategory("sports")}>Sports</p>
  <div className="dropdown-divider"></div>
  <p className="dropdown-item cursor-pointer" onClick={() => this.setCategory("general")}>General</p>
</div>
  1. 修复setState的日志问题:如果需要查看更新后的分类状态,使用setState的第二个回调参数(该回调会在状态更新完成后执行):
// App.js中的setCategory修改为:
setCategory = (cat)=> {
  this.setState({
    category: cat
  }, () => {
    console.log(this.state.category) // 这里打印的是更新后的状态
  })
}
  1. 简化Navbar代码(可选):Navbar的constructor中this.setCategory = this.props.setCategory没必要保留,直接使用this.props.setCategory即可,或者在箭头函数中直接调用this.props.setCategory("xxx")。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 05:50:26