两个问题:

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

    构造函数( Prop ){ 基础( Prop ) //props 已经具有来自“mapStateToTprops”的值 }

为什么这是自动完成的?

  • 并非每个 mapStateToProps 都会调用 ComponentWillReceiveProps(首次加载时就是这种情况)请参阅此链接 enter link description here
  • 更新 1

    如果我想写一个条件,例如:

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

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

    请您参考如下方法:

    mapStateToProps 不会在构造函数之前神奇地调用。它是由 connect 完成的这是 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.


    评论关闭
    IT虾米网

    微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!