首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当父组件的状态改变时,如何在React中更新(重新渲染)子组件?

当父组件的状态改变时,如何在React中更新(重新渲染)子组件?
EN

Stack Overflow用户
提问于 2019-11-23 17:19:40
回答 3查看 11.7K关注 0票数 5

好吧,我已经知道一种方法了。然而,我问这个是为了防止我重新发明轮子,因为我是一个非常新的反应。我的印象是,如果父组件通过道具将其状态传递给子组件,而不是在更新父组件的状态时,子组件将在需要时重新渲染。但事实似乎并非如此。我举了个例子,

代码语言:javascript
复制
class Child extends Component {
  constructor(props) {
    super(props);
    this.state = {
      number: props.number,
    };
  }

  updateNumber(n) {
    this.setState({number: n});
  }

  render() {
    return (<h1>{this.state.number}</h1>);
  }
}

class Parent extends Component {

  constructor(props) {
    super(props);
    this.state = {
      number: -1,
    };
    this.child = React.createRef();
    setInterval(this.updateState.bind(this), 1000);
  }

  updateState() {
    console.log(this.state);
    this.setState({
      number: Math.floor((Math.random() * 10) + 1),
    });
    // this.child.current.updateNumber(this.state.number);
  }

  render() {
    return (
      <div>
        <Child ref={this.child} number={this.state.number}/>
      </div>
    );
  }
}

在本例中,除非我显式定义一个引用并使用它来调用子对象的更新函数(注释部分),否则不会在每次更新父对象的状态时重新呈现该子对象。就这样了吗?你是打算手动更新你的孩子的状态(嘿),还是如果他们的父母的状态作为道具传递给他们,他们应该自动更新(并因此重新渲染)。

EN

Stack Overflow用户

发布于 2019-11-23 17:44:41

你的方法是错误的,不要像这样从子状态更新你的父状态,也不要在子状态中保存道具,它们已经随着父状态的更新而更新。

如果你想更新父窗体,子窗体传递道具,像this.when父窗体更新一样,子窗体也会更新。

代码语言:javascript
复制
class Child extends Component {
  constructor(props) {
    super(props);
  }

updateNumber=()=>{// update parent form child. call this function in somewhere in your component. if you want to pass event pass it as second argument
  this.props.updateNumber(newUpdatedNumber,event);
}

  render() {
    return (<h1>{this.props.number}</h1>);
  }
}

class Parent extends Component {

  constructor(props) {
    super(props);
    this.state = {
      number: -1,
    };
    this.child = React.createRef();
    setInterval(this.updateState.bind(this), 1000);
  }

  updateState() {
    console.log(this.state);
    this.setState({
      number: Math.floor((Math.random() * 10) + 1),
    });
  }
//update parent from child

  updateParentFromChild=(updatedNumber,event)=>{//catch function from child 
   this.setState({
      number:updatedNumber
   });
  }


  render() {
    return (
      <div>
        <Child ref={this.child} updateNumber={this.updateParentFromChild} number={this.state.number}/>
      </div>
    );
  }
}
票数 1
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59006178

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档