簡體   English   中英

當父組件的狀態發生變化時,如何更新(重新渲染)React 中的子組件?

[英]How to update (re-render) the child components in React when the parent's state change?

好的,我已經知道一種方法來做到這一點。 但是,我問這個以防萬一我重新發明輪子,因為我對 React 非常陌生。 我的印象是,如果父組件通過 props 將她的狀態傳遞給子組件而不是更新父組件的狀態,那么子組件將在需要時重新渲染。 但情況似乎並非如此。 我設置了這個例子,

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

在這個例子中,除非我明確定義一個引用並使用它來調用子級的更新函數(注釋部分),否則每次更新父級的狀態時都不會重新渲染子級。 所以是這樣嗎? 如果他們的父母的狀態作為道具傳遞給他們,你是否應該手動更新你的孩子的狀態(heh)或者他們應該自動更新(並因此重新渲染)。

重新渲染子項的一個簡單選擇是在每次需要重新渲染時更新唯一的鍵屬性。

<ChildComponent key={this.state.updatedKey}/>

這是因為您的 Child 組件也在使用它自己的狀態。 總是問自己state是否必要,這是 React 初學者的常見錯誤。

希望您通過查看此示例可以更深入地了解它。 而不是調用的setInterval在構造函數中,我會建議你把它調用componentDidMountclearIntervalcomponentWillUnmount

// Since you are not using state, you can use functional component for your Child component
const Child = ({ number }) => <h1>{number}</h1>;

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.timer = null;
    this.state = { number: 0 };
  }

  componentDidMount() {
    // setInterval after component did mount
    this.timer = setInterval(this.incrementNumber, 1000);
  }

  componentWillUnmount() {
    // clearInterval when component is going to unmount
    if (this.timer) {
      clearInterval(this.timer);
    }
  }

  incrementNumber = () => {
    // setState function callback to ensure state received will be latest state
    this.setState(prevState => ({ number: prevState.number + 1 }));
  }

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

你的方法是錯誤的,不要像這樣從孩子更新你的父狀態,也不要在子狀態中保存道具,它們已經隨着父更新而更新。

並且如果您想更新父表單子將道具表單子傳遞給父像這樣。當父更新時,子也會更新。

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

暫無
暫無

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

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