【问题标题】:componentWillReceiveProps is not called on redux props change在 redux 道具更改时不调用 componentWillReceiveProps
【发布时间】:2018-07-19 05:46:10
【问题描述】:

我的组件很简单:

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 就没有被调用一次。

是什么原因造成的?

【问题讨论】:

  • 我猜这与您的 mapStateToProps 返回的内容有关,您应该将一些日志放在那里,并确保您不会一遍又一遍地返回相同的实例。这将使您的组件不会更新,因为道具没有改变。最好不要在 mapStateToProps 中执行操作
  • @EricHasselbring 起初它是一个空对象,当实例被加载时,它包含实例数据。
  • 如果您记录 shouldComponentUpdate 并将 (nextProps, nextState) 与 current 进行比较,您会发现差异吗?
  • 它也永远不会被调用。 @EricHasselbring
  • 生命周期如下:"constructor, will mount, render, did mount" x3

标签: reactjs react-redux redux-thunk


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 2017-03-22
    • 2018-05-08
    • 1970-01-01
    相关资源
    最近更新 更多