I have a simple router (started with redux-router
and switched to react-router
to eliminate variables).
<Router history={history}>
<Route component={Admin} path='/admin'>
<Route component={Pages} path='pages'/>
<Route component={Posts} path='posts'/>
</Route>
</Router>
Admin component is basically just {this.props.children}
with some nav; it is not a connect
ed component.
Pages component is a connect
ed component with mapStateToProps()
like so:
function mapStateToProps (state) {
return {
pages: state.entities.pages
};
}
Posts is even more interesting:
function mapStateToProps (state) {
let posts = map(state.entities.posts, post => {
return {
...post,
author: findWhere(state.entities.users, {_id: post.author})
};
}
return {
posts
};
}
And then when I load the page or switch between Posts/Pages routes I get the following in my console.log().
// react-router navigate to /posts
Admin render()
posts: map state to props
Posts render()
posts: map state to props
Posts render()
posts: map state to props
// react-router navigate to /pages
Admin render()
pages: map state to props
Pages render()
pages: map state to props
So my question is: why is mapStateToProps
being called multiple times on route changes?
Also, why does a simple map
function in mapStateToProps
cause it to be called a third time in the Posts container?
I am using the basic logger
and crashReporter
middlewares from the Redux docs and it is not reporting any state changes or crashes. If the state isn't changing why are the components rendering multiple times?
As the first argument passed in to connect , mapStateToProps is used for selecting the part of the data from the store that the connected component needs. It's frequently referred to as just mapState for short. It is called every time the store state changes.
To solve the error "Module not found: Error: Can't resolve 'redux'", make sure to install the redux package by opening your terminal in your project's root directory and running the command npm install redux react-redux and restart your development server.
mapStateToProps() is a function used to provide the store data to your component. On the other hand, mapDispatchToProps() is used to provide the action creators as props to your component.
The mapStateToProps(state, ownProps) is specified as the first argument of connect() call and its ownProps parameter receives the props object of the wrapper component. If the ownProps parameter is not present, React Redux skips calling the function at the props change.
Reselect allows you to create memoized selector functions for derived state processing.
Redux's documentation explains with an example how to use it. The repo's readme have a quick example too.
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