首页 > 解决方案 > 父状态更改时子组件不更新

问题描述

我有一个状态为数组的父组件,该数组也会随着时间的推移而添加。

这是父母。其中发生了很多事情,但我已将其提炼为主要关注状态、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在初始渲染后重新渲染为道具。无论父级重新渲染或更新它的状态多少次,该道具仍然是一个空数组。

标签: reactjs

解决方案


您的 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 的更多信息


推荐阅读