Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Redux - Why mapStateToProps is called before constructor?

Two questions:

  1. Why mapStateToProps is called before constructor?
  2. As a side-effect of 1

    constructor (props) { base(props) // props already have values from "mapStateToTprops" }

why that is being done automagically?

  1. Not every mapStateToProps invokes ComponentWillReceiveProps (this is the case when it loads first time) See this link enter link description here

Update 1

If I want to write a condition like:

if (props.isAuthenticated) { browserHistory.push("/admin/dashboard") }

Which method will be most suitable to hook. Keep in mind that I want to enforce this condition on each state change (because according to leo's answer ComponentWillReceiveProps is not reliable)?

like image 463
Cristian E. Avatar asked Sep 21 '16 14:09

Cristian E.


People also ask

Why we use mapStateToProps in Redux?

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.

What is mapStateToProps ()?

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.

What is the difference between mapStateToProps () and mapDispatchToProps ()?

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.

What do mapStateToProps and mapDispatchToProps actually do?

The mapStateToProps and mapDispatchToProps deals with your Redux store's state and dispatch , respectively. state and dispatch will be supplied to your mapStateToProps or mapDispatchToProps functions as the first argument.


1 Answers

mapStateToProps is not called magically before your constructor. It is done by connect which is a Higher Order Component that executes mapStateToProps before your component is initialised. In fact, connect initialises your component in its body.

connect(mapStateToProps, mapDispatchToProps)(YourComponent)

Why componentWillReceiveProps not executed? Because React doesn't call componentWillReceiveProps for the initial render, so you should use componentDidMount instead.

componentWillReceiveProps

Invoked when a component is receiving new props. This method is not called for the initial render.

like image 86
Lyubomir Avatar answered Nov 16 '22 03:11

Lyubomir