React Redux - Why mapStateToProps is called before constructor?

强颜欢笑 提交于 2019-12-21 04:35:16

问题


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)?


回答1:


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.



来源:https://stackoverflow.com/questions/39618767/react-redux-why-mapstatetoprops-is-called-before-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!