reactjs - 父状态更改时子组件不更新
问题描述
我有一个状态为数组的父组件,该数组也会随着时间的推移而添加。
这是父母。其中发生了很多事情,但我已将其提炼为主要关注状态、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>
);
}
}
据我所知,GaitStat 不会this.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 的更多信息
推荐阅读
- android - 运行 flutter clean 后项目抛出 gradle 错误
- javascript - discord.js:TypeError:无法读取未定义的属性“memberCount”
- javascript - 在功能组件中反应原生 typeScript 和 forwardRef
- terraform - 如何在 Terraform 中表示自定义 GCP 机器类型?
- java - Firestore 异步 API 在 readData 之外获取空值
- stormcrawler - Stormcrawler 没有从网页中检索所有文本内容
- javascript - 如何在 Postman 中设置过去的日期并添加 1 天
- r - 安装 phylosmith 失败 - 无法加载共享对象,未定义符号
- django - 如何重命名 Django 设置目录?
- javascript - 如何从后台页面上下文设计迁移到服务工作者在其他上下文设计之间传递消息?