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

React+Redux中Connect无法更新组件状态问题求助

问题分析与解决

嘿,我一眼就发现两个核心问题导致你的组件没能同步Redux Store的状态,咱们逐个解决:

1. 错误的State结构引用(最关键)

你用combineReducers把firstRedus作为根State的一个键,所以整个Store的State结构是这样的:

{
  firstRedus: {
    test: 'xxx',
    test2: 'xxx'
  }
}

但你的mapStateToProps里直接取state.test,这相当于在根State里找test属性,自然拿不到值。必须通过你定义的Reducer键来访问:

修改后的mapStateToProps:

function mapStateToProps(state){
  return {
    test: state.firstRedus.test, // 加上firstRedus前缀
    test2: state.firstRedus.test2 // 如果需要用到test2的话
  }
};

2. 不必要的State存储导致数据不同步

你在组件的constructor里把this.props.test赋值给this.state.test,但constructor只会在组件初始化时执行一次。之后Redux Store更新导致props.test变化时,组件的state.test不会自动更新——因为React不会主动把新props同步到state里。

解决方法很简单:直接使用props里的值,不用存到state中:

修改后的App组件片段:

class App extends PureComponent {
  constructor(props) {
    super(props)
    // 删掉这行:this.state = { test: this.props.test }
    this.handleClick1= this.handleClick1.bind(this);
    this.handleClick2= this.handleClick2.bind(this);
  }

  // ... 其他方法保持不变

  render() {
    return (
      <div className="App">
        <ul>
          {/* 直接使用props中的值 */}
          <li>{this.props.test}</li>
        </ul>
        <button onClick={this.handleClick1}>test1</button>
        <button onClick={this.handleClick2}>test2</button>
      </div>
    );
  }
}

额外小优化:简化mapDispatchToProps

你当前的mapDispatchToProps写法没问题,但可以更简洁——connect函数支持直接传入一个包含action creators的对象,它会自动帮你调用bindActionCreators:

// 替换原来的mapDispatchToProps
export default connect(
  mapStateToProps,
  { actFirst, actSec } // 直接传action creators即可
)(App);

做完这些修改后,你的组件应该就能正确同步Redux Store的状态了。另外提一句:你的Reducer里用Object.assign返回新对象的写法是正确的,保证了状态的不可变性,这点做得很好~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:21:56