[英]How to compare props in ComponentDidUpdate for large data structure connected with Redux
I've been working with new lifecycles of React v16.我一直在研究 React v16 的新生命周期。 It works great when we compare only a single key.当我们只比较一个键时,它非常有效。 But when it comes to compare a large data structures like an Arrays of objects, the deep comparison will become very costly.但是当要比较像对象数组这样的大型数据结构时,深度比较将变得非常昂贵。
I have use case like this in which I have an array ob objects stored in redux,我有这样的用例,其中我有一个存储在 redux 中的数组 ob 对象,
const readings =[
{
id: ...,
name: ...',
unit:...,
value: ...,
timestamp: ...,
active: true,
},
...
]
Whenever active state of any objects get changed I dispatch an action to update redux state to be same for all connected components with that reducer.每当任何对象的活动状态发生变化时,我都会调度一个动作来更新 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));
How can I avoid infinite loop on setState in componentDidUpdate, I don't want to do deep comparison of readings array.如何避免 componentDidUpdate 中 setState 的无限循环,我不想对读数数组进行深入比较。 Is there a better solution to handle this case?有没有更好的解决方案来处理这种情况?
Your suggestions will be highly appreciated.您的建议将不胜感激。
Ideally, you make immutable changes to your reducer and keep the reducer state level low.理想情况下,您对减速器进行不可变的更改并保持减速器状态级别较低。
So if your array consists of many objects and you need to dispatch based on some attribute change, you should replace the whole readings array using spread operator or using some immutable library eg immutablejs.因此,如果您的数组由许多对象组成,并且您需要根据某些属性更改进行调度,您应该使用扩展运算符或使用一些不可变库(例如 immutablejs)替换整个读数数组。 Then in your componentDidupdate you can have something like :然后在你的 componentDidupdate 你可以有类似的东西:
componentDidUpdate(prevProps) {
const {
readings,
} = this.props
const {
readings: prevReadings,
} = prevProps
if (readings !== prevReadings) {
//dispatch something
}
}
Thanks feedbacks are welcome.谢谢,欢迎反馈。
First read another answer, If that didn't work for you, then:首先阅读另一个答案,如果这对您不起作用,那么:
componentDidUpdate(prevProps){
if(JSON.stringify(prevProps.todos) !== JSON.stringify(this.props.todos){...}
}
let newtodos = JSON.parse(JSON.stringify(this.state.todos));
newtodos[0].text = 'changed text';
this.setState({ todos : newtodos });
(Note that Shallow clone doesn't work, since that way you change the objects directly) (请注意,浅克隆不起作用,因为这样可以直接更改对象)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.