我的组件很简单:

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


我非常确定我的reducer不会改变状态:

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


我肯定知道触发道具的状态更改是因为我在render方法上登录了this.props,并且道具更改了两次!
这样,componentWillReceiveProps甚至都没有被调用过。

是什么原因造成的?

最佳答案

有一些原因将导致不调用componentWillReceiveProps的原因,


如果未从redux商店接收到新的props对象
此外,如果安装了组件,则不会调用这些方法。因此,您可能会看到组件更新,但实际上只是安装和卸载。要解决此问题,请查看渲染该组件的父级,并检查它是否正在使用其他键渲染该组件,或者是否存在某种条件渲染,该渲染可能返回false并导致对其进行卸载。

关于reactjs - 在redux Prop 更改时未调用componentWillReceiveProps,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48689169/

10-11 10:22
查看更多