React使用componentWillReceiveProps重新呈现组件

pbg*_*gnz 14 reactjs redux

我无法弄清楚如何在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)

  • 在这种情况下,@ pbgnz只是一起删除状态并使用`this.props.user`而不是`this.state.user`.如果其道具或状态发生变化,您的组件将始终重新渲染.如果组件将根据某些操作(无论是用户还是从api调用加载数据)而改变,那么您应该只使用state. (4认同)