【发布时间】:2020-02-13 17:49:55
【问题描述】:
父组件在收到新的 props 时会重新渲染,但其子组件不会重新渲染。子组件仅第一次渲染,从不重新渲染,也不从 redux store 接收 props
我在父组件中从 redux 存储中获取更新的数据,但在子组件中没有。子组件只有在第一次渲染时才从 redux store 接收数据
我的父组件Home.js
对象 seaFCLJSON 看起来像这样
const seaFCLJSON ={"rates": {"sort":"faster", "someOther": "someOtherValues"}};
当 redux 存储更新时,seaFCLJSON 看起来像这样
const seaFCLJSON ={"rates": {"sort":"cheaper","someOther": "someOtherValues"}};
class Home extends Component {
state = {
seaFCLJSON: {}
};
componentDidMount = () => {
this.setState({ seaFCLJSON: this.props.seaFCLJSON });
};
componentWillReceiveProps = nextProps => {
if (this.state.seaFCLJSON !== nextProps.seaFCLJSON) {
this.setState({ seaFCLJSON: nextProps.seaFCLJSON });
}
};
render() {
const { seaFCLJSON } = this.props;
return (
<>
{!isEmpty(seaFCLJSON) && seaFCLJSON.rates && seaFCLJSON.rates.fcl ? (
<FCLContainer fclJSON={seaFCLJSON} />
) : null} //it never rerenders upon getting updated data from redux store
<h5>{JSON.stringify(seaFCLJSON.rates && seaFCLJSON.rates.sort)}</h5> //it rerenders everytime upon getting updated data from redux store
</>
);
}
}
const mapStateToProps = state => {
return {
seaFCLJSON: state.route.seaFCLJSON
};
};
export default connect(
mapStateToProps,
actions
)(Home);
isEmpty.js
export const isEmpty = obj => {
return Object.entries(obj).length === 0 && obj.constructor === Object;
};
我的子组件FCLContainer.js
class FCLContainer extends Component {
state = {
seaFCLJSON: {}
};
componentDidMount = () => {
this.setState({ seaFCLJSON: this.props.seaFCLJSON });
};
componentWillReceiveProps = nextProps => {
console.log("outside state value: ", this.state.seaFCLJSON);
if (this.state.seaFCLJSON !== nextProps.seaFCLJSON) {
this.setState({ seaFCLJSON: nextProps.seaFCLJSON });
console.log("inside state value: ", this.state.seaFCLJSON);
}
};
render() {
const { seaFCLJSON } = this.state;
console.log("rendering .. parent props: ", this.props.fclJSON);
console.log("rendering .. redux store props: ", this.props.seaFCLJSON);
return (
<>
<div className="home-result-container">
<div>
<h5>This child component never rerenders :(</h5>
</div>
</div>
</>
);
}
}
const mapStateToProps = state => {
return {
seaFCLJSON: state.route.seaFCLJSON
};
};
export default connect(
mapStateToProps,
actions
)(FCLContainer);
不知道是Parent组件有问题还是子组件有问题。 componentWillReceiveProps 在父组件中被调用,但在子组件中不被调用。请忽略任何缺少的分号或大括号,因为我省略了一些不必要的代码。
编辑 1:我只是出于调试目的将 props 中的值复制到 state 中。
感谢您的帮助。谢谢。
编辑 2:我在 redux 操作中直接更改了一个对象。这就是CWRP没有被解雇的原因。这就是问题所在。有关更多信息,请查看下面的答案。
【问题讨论】:
标签: javascript reactjs redux react-redux redux-thunk