簡體   English   中英

React使用componentWillReceiveProps重新渲染組件

[英]React use componentWillReceiveProps to re-render the component

this.props.user的值更改時,我不知道如何重新渲染我的componenet。 最初, this.props.user值為null,但幾秒鍾后更改為實際值。 下面我顯示了子組件。 父組件將商店狀態映射到其道具,然后將其傳遞給下面的子組件類。

export class UserInfoComponent extends Component {
  constructor(props){
    super(props);
    this.state = {user: this.props.user}
  }

  componentWillReceiveProps(){
    this.setState({user: this.props.user})
  }

  render() {
    if(this.state.user)
    return (
      <h1>{this.state.user.firstName}</h1>
    );

    return (
      <h1>loading</h1>
    )
  }
}

componentWillReceiveProps接收nextProps作為參數。 使用您當前擁有的代碼,您只是將用戶設置為當前狀態。 您需要使用提供的nextProps參數。

export class UserInfoComponent extends Component {
  constructor(props){
    super(props);
    this.state = {user: this.props.user}
  }

  componentWillReceiveProps(nextProps){
    this.setState({user: nextProps.user})
  }

  render() {
    if(this.state.user)
    return (
      <h1>{this.state.user.firstName}</h1>
    );

    return (
      <h1>loading</h1>
    )
  }
}

暫無
暫無

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

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