I'm having a little problem with connect(). I thought wrapping all components in Provider is going to work, but turns out it isn't.... So I found that I need to use connect() from react-redux. The problem is i don't know how should I use it. This site is showing some examples but, i don't have any action creators to put inside connect because I don't use them....... Can someone give me some advices? I just want to access my store inside components...
In order to use your store in your container you need to do two things
Firstly : make use of mapStateToProps()
.
As the name suggests, it maps the state variables from your store to the props that you specify
Secondly : You need to connect these props
to your container. This is where connect()
comes into picture. The object returned by the mapStateToProps
component is connected to the container. You can import connect from react-redux
like import {connect} from 'react-redux';
Example
import React from 'react';
import { connect } from 'react-redux';
class App extends React.Component {
render() {
return <div>{this.props.containerData}</div>;
}
}
function mapStateToProps(state) {
return { containerData: state.appData };
}
export default connect(mapStateToProps)(App);
You might have better luck with the Redux documentation here.
Here's a simple example of how the connect function works:
import React from 'react';
import { connect } from 'react-redux';
class Item extends React.Component {
render() {
return <div onClick={() => this.props.dispatch( /* some action here */ )}>{this.props.name}</div>;
}
}
function mapStateToProps(state) {
return { name: state.name };
}
export default connect(mapStateToProps)(Item);
What happens above is when you export the Item
component, you're exporting the wrapped, connected component. Wrapping the component will pass in the prop name
from the app state (it will also pass in the dispatch
function as a prop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With