首页 文章

ReactJs Child Component未通过Props更新

提问于
浏览
2

目标:通过从父级的非状态变量发送道具,仅重新渲染子组件 .

我想重新渲染没有父渲染的子组件 . 下面是我写的示例代码 . cRoot是父级传递道具,CButton子组件需要在更改Visibility变量时呈现 .

  • 在子组件中,我没有想要将该值保持在状态 . 也是Child我不想创建Pure组件 .

  • 在父级中,我想使用变量(submitBtnVisibility)作为道具发送 .

你能否解释为什么子组件没有得到更新,因为子组件的观点道具正在更新?还是指着我哪里出错了?

非常感谢您的帮助 .

// 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>;
  }
}

1 回答

  • 3

    想想看,你的Child组件如何重新渲染?如果它的道具或状态发生变化 . 好了,现在想想你的父组件如何将其改变的道具传递给你的子组件?什么时候重新渲染 .

    父组件如何重新渲染?当然它的状态发生变化(或道具,但对于父母来说,现在没有任何道具)当然 . 因此,您不会更改父级的状态,也不会重新渲染 . 所以,你的孩子不会重新渲染 . 很简单 .

    您不能渲染子组件,除非它获得父级上方的新道具 . 除非其状态(或道具)发生更改,否则父级不会重新呈现 . 在这里,你没有做这些 .

    Update after comments

    除非渲染父组件,否则无法渲染子项 . 父母没有变化,因此没有为孩子退保 .

    不要害怕渲染这么多 . 渲染本身并不是那么昂贵,DOM的变化也是如此 . React比较DOM(虚拟的和真实的),如果没有改变,它不会卸载/重新安装组件 .

    另外,我不想 PureComponent 但它提供了你想要的功能 . 除此之外,您可以使用 shouldComponentUpdate ,但大多数人不建议使用它,因为它有其他缺点,如果使用不当,它会降低性能而不是降低性能 .

相关问题