簡體   English   中英

更改父狀態時如何防止子組件重新加載

[英]how to prevent child component from reload when the parent state is change

在一種情況下,父組件將imgkey props發送給子組件。 當子組件加載該圖像時,它可以更改img並通過回調更改其狀態以返回到父級。

現在父組件具有其他功能,並且當其他功能更改狀態時,子組件(圖像)每次都會加載。如何防止在相同的imgkey道具上重新加載?

總的來說,當父級發送與之前發送的道具相同的imgkey ,子級不應重新加載

我相信,如果孩子需要:

  • 保持渲染或跟進一些邏輯; 要么
  • 它是可有可無的,我們可以跳過渲染它

兒童

該組件將繼續渲染,有時僅在需要時運行一些邏輯。

class Child extends Component {
  static getDerivedStateFromProps(props, state) {
    if (props.id % 10 === 0) {
      return { shouldRunLogic: true };
    }
    return { shouldRunLogic: false };
  }
  constructor(props, context) {
    super(props, context);
    this.state = { shouldRunLogic: false };
  }
  componentDidMount() {
    // Let's do our stuff once DOM mounted
    this.handleSomeLogic();
  }
  componentDidUpdate(prevProps, prevState) {
    // Do we need to call our logic again?
    if (this.state.shouldRunLogic) {
      this.handleSomeLogic();
    }
  }
  handleSomeLogic() {
    // do some stuff
    this.props.onFinish('Child finished the logic');
  }
  render() {
    // Makes sure we always render for children if any
    return <div>{this.props.id}-{this.props.children}</div>;
  }
}

可分配兒童

該組件僅做一件事,並且在邏輯完成后再也不會重新渲染。

class DispensableChild extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = { isComplete: false };
  }
  componentDidMount() {
    // Let's do our stuff once DOM mounted
    this.handleSomeLogic();
  }
  shouldComponentUpdate(nextProps, nextState) {
    return !this.state.isComplete;
  }
  handleSomeLogic() {
    // do some stuff
    // ...
    // Let's make sure this component never render again
    this.setState({ isComplete: true }, () => this.props.onFinish('DispensableChild finished the logic'));
  }
  render() {
    return this.state.isComplete || <div>Doing some logic</div>;
  }
}

父母

包含兩個子組件,但只有“子”組件將繼續渲染。

class Parent extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = { childId: 1 };
    this.handleFinish = this.handleFinish.bind(this);
  }
  componentDidMount() {
    // Let's pass the prop every 15 secs
    setInterval(() =>
      this.setState(({ childId }) => ({ childId: childId + 1})), 15000);
  }
  handleFinish(message) {
    console.log(message);
  }
  render() {
    return (
      <div>
        <Child id={this.state.childId} onFinish={this.handleFinish} />
        <DispensableChild id={this.state.childId} onFinish={this.handleFinish} />
      </div>
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM