I have a single component App.js
where I trying to save state using redux
. In index.js where I set store for only <App />
component.
index.js
let store = createStore(scoreReducer);
ReactDOM.render(
<Provider store={store}><App /></Provider>,
document.getElementById("root")
);
registerServiceWorker();
I have this method in App.js
to map state to props which is available inside App.js
.
App.js
function mapStateToProps(state) {
return { score: state.score, status: state.status };
}
Everything is well so far, now I am not sure how to access { this.props.score}
in another component ?
What changes I need to do in index.js
and second component if I want to access {this.props.score}
in another component ?
When you are using Provider any component that is children of the Provider Higher Order Component can access the store properties though the use of
connect
function.So you can add the following in any component that is a child of Provider and access the score prop
However if this other component is a direct child of
App
component then you can also pass thescore prop
as aprop
to this component from App likeProvider
component sets the context for all its children, providing the store in it. when you use the High Order Component(HOC)connect
you can wrap any component and access the store through the providedmapStateToProps
andmapStateToProps
no matter how nested they are. You can also access the store using contextcontext.store
but this is not recommended. Using map functions andconnect
, similar to what you have with yourApp
component, is the best approach.