简体   繁体   中英

How to get reference to store in react/redux?

In my reactjs-universal component I wrote this:

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.

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.

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.

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. This gives you access to the dispatch function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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