如何比较ComponentDidUpdate中与Redux连接的大型数据结构的道具



我一直在研究React v16的新生命周期。当我们只比较一个键时,效果很好。但是,当涉及到比较像对象数组这样的大型数据结构时,深度比较将变得非常昂贵。

我有这样的用例,其中我有一个存储在redux、中的对象数组

const readings =[
{
id: ...,
name: ...',
unit:...,
value: ...,
timestamp: ...,
active: true,
},
...
]

每当任何对象的活动状态发生变化时,我都会调度一个操作,将redux状态更新为与该reducer连接的所有组件相同。

class Readings extends Component {
state = {
readings:[],
};
static getDerivedStateFromProps(nextProps, prevState) {
if ( // comparsion of readings array with prevState) {
return {
readings: nextProps.readings,
};
}
return null;
}
componentDidUpdate(prevProps) {
if ( // comparsion of readings array with prevState) {
// perform an operation here to manipulate new props and setState to re render the comp
// this causes infinite loop
}
}
render() {
...
}
}
const mapStateToProps = state => ({
readings: state.readings.readings,
});

export default connect(
mapStateToProps,
)(Readings));

如何避免componentDidUpdate中setState的无限循环,我不想对reads数组进行深入比较。有更好的解决方案来处理这个案子吗?

我们将非常感谢您的建议。

理想情况下,您可以对您的reducer进行不可变的更改,并保留减速器状态级别低。

因此,如果您的数组由许多对象组成,并且需要根据某些属性更改进行调度,则应使用spread运算符或使用一些不可变的库(如immutablejs(来替换整个reads数组。然后在你的组件Didvpdate中,你可以有这样的东西:

componentDidUpdate(prevProps) {
const {
readings,
} = this.props
const {
readings: prevReadings,
} = prevProps
if (readings !== prevReadings) {
//dispatch something
}
}

欢迎反馈感谢。

首先阅读另一个答案,如果这对你不起作用,那么:

  1. 请确保将两个数组与:
componentDidUpdate(prevProps){
if(JSON.stringify(prevProps.todos) !== JSON.stringify(this.props.todos){...}
}
  1. 确保在深度克隆后更改传递的道具(父级中的状态(:
let newtodos = JSON.parse(JSON.stringify(this.state.todos));
newtodos[0].text = 'changed text';
this.setState({ todos : newtodos });

(请注意,Shallow克隆不起作用,因为这样可以直接更改对象(

最新更新