React Redux - 为什么在构造函数之前调用 mapStateToProps?

React Redux - Why mapStateToProps is called before constructor?

两个问题:

  1. 为什么在构造函数之前调用mapStateToProps
  2. 作为 1

    的副作用

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

为什么这是自动完成的?

  1. 并非每个 mapStateToProps 都会调用 ComponentWillReceiveProps(这是第一次加载时的情况)请参阅此 link enter link description here

更新 1

如果我想写这样的条件:

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

哪种方法最适合hook。请记住,我想在每次状态更改时强制执行此条件(因为根据 leo 的 回答 ComponentWillReceiveProps 不可靠)?

mapStateToProps 不会在构造函数之前神奇地调用。它由 connect which is a Higher Order Component 在您的组件初始化之前执行 mapStateToProps 完成。事实上,connect 会在其主体中初始化您的组件。

connect(mapStateToProps, mapDispatchToProps)(YourComponent)

为什么componentWillReceiveProps没有执行?因为 React 不会为初始渲染调用 componentWillReceiveProps,所以您应该使用 componentDidMount

componentWillReceiveProps

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