ckinmind / react-cnode

👨🏻‍💻React构建的cnode社区(附详细问题说明)
https://ckinmind.github.io/react-cnode
15 stars 7 forks source link

关于componentWillReceiveProps的触发的问题(redux中) #22

Open ckinmind opened 7 years ago

ckinmind commented 7 years ago

1. componentWillReceiveProps不触发

背景::在登陆场景,如果登录成功,通过reduer会更新store中User的isLogine为true,则componentWillReceiveProps会接收到新的数据,从而更新组件状态 但是如果登陆失败,我在reducer直接返回原来的state,这时候componentWillReceiveProps不触发,因为没有接受到新的数据

ckinmind commented 7 years ago
  1. componentWillReceiveProps和componentWillMount在组件初始化的时候一起触发了

    背景:进入登录页后直接触发了componentWillMount 和 componentWillReceiveProps,代码如下

  /** 登录成功后再次访问登录页时跳转到个人中心)*/
    componentWillMount() {
        console.log('componentWillMount');
        let { isLogined, loginname } = this.props.User;
        if (isLogined){
            hashHistory.push({ pathname: '/user/' + loginname });
        }
    }

 /** 当登录成功,SignIn组件或接受到新的User数据,然后根据isLogined来决定跳转到个人中心还是清空输入框 */
    componentWillReceiveProps(nextProps){
        console.log('componentWillReceiveProps');
        let { isLogined, loginname, onLogining } = nextProps.User;
        if(isLogined){
            /* 登录成功跳转 */
            hashHistory.push({ pathname: '/user/' + loginname });
        }else if(!onLogining){
            /** 这里if生效的条件是未登录且不处于登录状态*/
            this.tokenInput.value = '';
            alert('登录失败');
        }
    }

还没登录进入登录页,结果直接弹出了登录失败,SignIn刚刚初始化不应该会触发componentWillReceiveProps

如果是刷新当前登录页,则不会触发componentWillReceiveProps,因为组件的节点初次载入时不会触发componentWillReceiveProps,react就是这么设计的; 但是奇怪的是如果是从其他页面进入登录页,则会触发componentWillReceiveProps,但是从其他页面进入登录页,登录页组件也是初次加载啊,为什么会触发componentWillReceiveProps,很奇怪