小编典典

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

reactjs

两个问题:

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

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

为什么要自动完成?

  1. 并非每次mapStateToProps调用ComponentWillReceiveProps(第一次加载时就是这种情况),请参阅此链接,在此处输入链接描述

更新1

如果我想写这样的条件:

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

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


阅读 280

收藏
2020-07-22

共1个答案

小编典典

mapStateToProps在构造函数之前没有被神奇地调用。它是通过connect完成的,connect是在组件初始化之前执行的高阶组件mapStateToProps。实际上,会connect初始化您体内的组件。

connect(mapStateToProps, mapDispatchToProps)(YourComponent)

为什么componentWillReceiveProps不执行?因为React不要求componentWillReceiveProps初始渲染,所以应该使用它componentDidMount

componentWillReceiveProps

组件接收新道具时调用。初始渲染不调用此方法。

2020-07-22