React Redux - 为什么在构造函数之前调用 mapStateToProps? [英] React Redux - Why mapStateToProps is called before constructor?

查看:51
本文介绍了React Redux - 为什么在构造函数之前调用 mapStateToProps?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个问题:

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

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

构造函数(道具){基地(道具)//props 已经有来自 "mapStateToTprops" 的值}

为什么会自动完成?

  1. 并非每个 mapStateToProps 都会调用 ComponentWillReceiveProps(这是第一次加载时的情况)请参阅此链接 在此处输入链接描述
  1. Not every mapStateToProps invokes ComponentWillReceiveProps (this is the case when it loads first time) See this link enter link description here

更新 1

如果我想写一个条件:

Update 1

If I want to write a condition like:

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

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

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

推荐答案

mapStateToProps 不会在构造函数之前神奇地调用.它由 connect 完成,它是一个 <执行 的 href="https://medium.com/@franleplant/react-higher-order-components-in-depth-cf9032ee6c3e#.nho2ygep2" rel="noreferrer">高阶组件mapStateToProps 在你的组件初始化之前.事实上,connect 在它的主体中初始化你的组件.

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)

<小时>

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


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.

这篇关于React Redux - 为什么在构造函数之前调用 mapStateToProps?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆