我有一个处于其状态的数组的父组件,随着时间的推移,该数组也会被添加。
这是父母。其中发生了很多事情,但我已经将其归结为主要关注的状态、componentShouldUpdate 函数(适用于组件需要执行的所有其他操作)以及同样适用的 show data 方法(我可以确认gaitStats
确实如此)正确更新)。
class GaitMeasure extends Component {
constructor(props) {
super(props);
this.state = {
grabData: null;
gaitStats: []
};
}
shouldComponentUpdate(nextProps) {
if (this.props.data !== null) {
if (this.props.data !== nextProps.data) {
this.showData();
}
return false;
}
if (this.props.canvas.x !== null) {
return true;
}
if (this.state.grabData) {
return true;
}
return false;
}
showData() {
....
const avgGait = [...this.state.gaitStats];
avgGait.push(Math.abs(rightX - leftX));
this.setState({
timeline: this.state.timeline + 3,
gaitStats: avgGait
});
// render
步态状态,孩子:
class GaitStat extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
Hi
<p>{this.props.gaitStats}</p>
</div>
);
}
}
据我所知,GaitStatthis.state.gaitStatus
在初始渲染后永远不会重新渲染为道具。无论父级重新渲染或更新其状态多少次,道具都保持为空数组。
您的 shouldComponentUpdate 方法会阻止类在状态更改时更新。您应该将 shouldComponentUpdate 方法更新为以下内容
shouldComponentUpdate(nextProps, nextState) {
if(nextState !== this.state){
return true;
}
if (this.props.data !== null) {
if (this.props.data !== nextProps.data) {
this.showData();
}
return false;
}
if (this.props.canvas.x !== null) {
return true;
}
if (this.state.grabData) {
return true;
}
return false;
}
您可以在此处找到有关 shouldComponentUpdate 的更多信息
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句