简体   繁体   English

如何在react / redux中引用存储?

[英]How to get reference to store in react/redux?

In my reactjs-universal component I wrote this: 在我的reactjs-universal组件中,我写了这样的:

const mapStateToProps = (store) => {
  return {
    cars: store
  }
}

export default connect(mapStateToProps)(SearchForm)

In the same component I would like to dispatch an action like : 在同一个组件中,我想发送一个动作,如:

 store.dispatch({type: 'SHOWDETAIL', data: 'hi'});

When this is run I get: 当这个运行时,我得到:

Uncaught TypeError: _create2.default.dispatch is not a function

Is it possible to get a reference to the store somehow in my component so I can dispatch the action? 是否有可能在我的组件中以某种方式获得对商店的引用,以便我可以发送操作?

connect will call mapStateToProps with the state as argument not the store. connect将调用mapStateToProps作为参数而不是商店。

It seems that in your case you don't need reference to the store, and using connect to map dispatch to the props is enough. 看来在你的情况下你不需要引用商店,并且使用connect to map dispatch到props就足够了。

const mapStateToProps = (store) => {
  return {
    cars: store
  }
}

const mapDispatchToProps = dispatch => {
  return {
    action : () => dispatch({
      type : 'ACTION_NAME'
    })
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(SearchForm)

If you really want the store you should just export it from where you create it and import it where you need it, it isn't the purpose of connect to pass the store. 如果你真的想要商店,你应该从你创建它的地方导出它并将它导入到你需要的地方,这不是connect传递商店的目的。

You don't get a reference to the store object, but to the state inside of the store. 您不会获得对商店对象的引用,而是对商店内部的状态的引用。 The second parameter of the connect function is mapDispatchToProps. connect函数的第二个参数是mapDispatchToProps。 This gives you access to the dispatch function. 这使您可以访问调度功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM