[英]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.