componentWillReceiveProps 不会在 redux 道具更改时调用

componentWillReceiveProps is not called on redux props change

我的组件很简单:

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;
    }
}

我确定触发 props 发生变化的状态变化是因为我在 render 方法上记录了 this.props,并且 props 发生了几次变化! 这样一来,componentWillReceiveProps 甚至一次都没有被调用。

是什么原因造成的?

componentWillReceiveProps 不会被调用的原因有几个,

  • 如果它没有从 redux store 接收到新的 props 对象
  • 此外,如果安装了组件,则不会调用这些方法。所以你可能会看到你的组件更新,但它实际上只是安装和卸载。要解决此问题,请查看渲染此组件的父级并检查它是否正在使用不同的键渲染组件,或者是否存在某种可能 return false 并导致卸载它的反应的条件渲染。