【发布时间】: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