簡體   English   中英

ReactJs子組件未通過道具更新

[英]ReactJs Child Component is not getting updated through Props

目標:通過從父級的非狀態變量發送道具,僅重新渲染子級組件。

我只想重新渲染子組件,而無需父渲染。 以下是我編寫的示例代碼。 cRoot是傳遞父項的道具,並且需要在更改Visibility變量時呈現CButton Child組件。

  • 在子組件中,我並沒有使用狀態,因為它曾經一次,而且我不想將該狀態保持在狀態中。 還有孩子,我不想創建為Pure組件。
  • 在父級中,我想使用變量(submitBtnVisibility)作為props發送。

您能否解釋一下為什么子組件未更新,因為子組件的觀點道具正在更新? 還是指着我哪里出問題了?

預先非常感謝您的幫助。

// Parent Component 

class Root extends React.Component {
  constructor(props) {
    super(props);
    this.state = { refresh: true };
    // Parents non-state variable.
    this.submitBtnVisibility = { visibility1: 1, visibility2: 2 };

  }

  componentDidMount() {
    console.log("Root componentDidMount ");
  }

  componentDidUpdate(prevProps, prevState) {
    console.log("Root componentDidUpdate ", prevProps, prevState);
  }

  handleonclick = () => {
    console.log(" Root Btn Clicked");
    //this.setState({ var1: 5 });  -> If I enable this line , child is getting rendered
    this.submitBtnVisibility.visibility1 = 5;
  };
  render() {
    console.log(" Root Render ");

    return (
      <div className={classes.uploadContainerArea}>
        <Btncomponent visibility={this.submitBtnVisibility} />
        <button className={classes.btnroot} onClick={this.handleonclick}>
          {" "}
          Root Btn{" "}
        </button>
      </div>
    );
  }
}

// Child Component 

class Btncomponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { Btnprops: this.props.visibility };
  }

  componentDidMount() {
    console.log("Btncomponent componentDidMount ");
  }

  componentDidUpdate(prevProps, prevState) {
    console.log("Btncomponent componentDidUpdate ", prevProps, prevState);
  }

  static getDerivedStateFromProps(props, state) {
    console.log(" getDerivedStateFromProps ");
    return null;
  }
  shouldComponentUpdate(nextProps, nextState) {
    console.log(" shouldComponentUpdate ");
    return true;
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    console.log(" getSnapshotBeforeUpdate ");
    return null;
  }
  render() {
    console.log(" Btncomponent Render ", this.props);

    return <button type="button"> {this.props.visibility.visibility1} </button>;
  }
}

考慮一下,您的Child組件如何重新渲染? 如果其道具或狀態發生變化。 好的,現在考慮一下您的父組件如何將其更改后的prop傳遞給子組件? 當它當然會退貨。

父組件如何重新呈現? 當然,當它的狀態改變時(或者是道具,但對於父項,現在沒有任何道具)。 因此,您不會更改父級的狀態,並且不會重新渲染。 因此,您的孩子不會重新渲染。 就這么簡單。

您不能渲染子組件,除非它在父組件之上獲得了新的道具。 除非其狀態(或道具)發生變化,否則父級不會重新渲染。 在這里,您不執行任何操作。

評論后更新

除非渲染父組件,否則無法渲染子組件。 父母沒有變化,孩子就沒有重新投降。

不要害怕渲染太多。 渲染本身並不那么昂貴,而DOM更改卻很昂貴。 React將DOM(虛擬的和真實的)進行比較,如果沒有任何變化,它不會卸載/重新安裝組件。

另外,我不知道您為什么不想使用PureComponent但是它提供了您想要的功能。 除了可以使用shouldComponentUpdate之外,還可以使用shouldComponentUpdate ,但是大多數人不建議使用它,因為它還有其他缺點,如果使用不當,則會降低性能而不是降低性能。

暫無
暫無

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

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