我无法弄清楚如何在this.props.user更改值时重新渲染我的componentsnet .最初的值为this.props.usernull,但它会在几秒后更改为实际值.下面我展示了儿童组件.父组件将商店状态映射到它的props,我将它传递给下面的子组件类.
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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
fin*_*req 31
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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22692 次 |
| 最近记录: |