在redux props更改时不调用componentWillReceiveProps

时间:2018-02-08 15:33:04

标签: reactjs react-redux redux-thunk

我的组件很简单:

// Most linux 
lsof -i :3001

// OSX
lsof -iTCP -sTCP:LISTEN -P

我的减速机,我很确定我没有改变状态:

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';

import * as instanceActions from '../../../store/instances/instancesActions';

class InstanceDetailsPage extends Component {

    componentWillReceiveProps(nextProps) {
        console.log('will receive props');
        if (nextProps.id !== this.props.id){
            this.updateInstanceDetails();
        }
    }

    updateInstanceDetails = () => {
        this.props.actions.loadInstance(this.props.instance);
    };

    render() {
        return (
            <h1>Instance - {this.props.instance.name}</h1>
        );
    }
}

function getInstanceById(instances, instanceId) {
    const instance = instances.filter(instance => instance.id === instanceId);
    if (instance.length) return instance[0];
    return null;
}

function mapStateToProps(state, ownProps) {
    const instanceId = ownProps.match.params.id;
    let instance = {id: '', name: ''};
    if (instanceId && state.instances.length > 0) {
        instance = getInstanceById(state.instances, instanceId) || instance;
    }
    return {
        instance,
    };
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(instanceActions, dispatch)
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(InstanceDetailsPage);

我肯定知道触发道具的状态更改因为我在渲染方法上记录了import * as types from '../actionTypes'; import initialState from '../initialState'; export default function instancesReducer(state = initialState.instances, action) { switch (action.type){ case types.LOAD_INSTANCES_SUCCESS: return action.instances.slice(); // I probably don't event need the .slice() here, but just to be sure. default: return state; } } 而且道具改变了几次! 有了这个,this.props甚至没有被召唤过一次。

导致这种情况的原因是什么?

1 个答案:

答案 0 :(得分:1)

为什么不会调用componentWillReceiveProps有几个原因,

  • 如果它没有从redux商店收到新的道具对象
  • 另外,如果安装了组件,则不会调用这些方法。因此,您可能会看到组件更新,但它实际上只是安装和卸载。要解决此问题,请查看父组件呈现此组件,并检查它是否使用不同的键呈现组件,或者是否存在可能返回false的某种条件呈现并导致反应卸载它。