简体   繁体   English

将状态作为道具传递给孩子会导致null

[英]Passing down state as props to child gives null

I have parent component where I make and API call and set state for an abject. 我在其中创建父组件,并调用API并设置对象的状态。 Then I pass this state as props to the child. 然后我将这种状态作为道具传递给孩子。 This is my code for the parent, 这是我给父母的代码,

class Header extends React.Component {

  constructor(props) {
    super(props);
    this.state = { user: null};

  }//end of constructor

  componentWillMount() {

    getUserData(url).then((result) =>{
      this.setState({user : result});
      console.log(this.state.user);


    });
  }
  render() {
    return (
      <div className="header">
        <Masthead user= {this.state.user} />

      </div>
    );
  }
}
export default Header;

This is the child, 这是孩子

class Masthead extends React.Component {

  constructor(props){
    super(props);
  }

  componentDidMount(){
    console.log(this.props.user);
  }
  render() {
    return (     
        <div className="col-md-8">
         ......
        </div>     
    );
  }
}
Masthead.propTypes ={
  user: React.PropTypes.object
};
export default Masthead;

I get null for the user object when I console log it in the child. 当我在子对象中进行控制台登录时,该用户对象为null What am I doing wrong? 我究竟做错了什么?

From the docs: 从文档:

componentWillMount() is invoked immediately before mounting occurs. 在挂载发生之前立即调用componentWillMount() It is called before render() , therefore setting state in this method will not trigger a re-rendering. 它在render()之前调用,因此在此方法中设置状态不会触发重新渲染。

In other words - even if the parent state will change in componentWillMount() , it won't affect children components. 换句话说-即使父状态将在componentWillMount()更改,也不会影响子组件。 Try to make your API call in componentDidMount() . 尝试在componentDidMount()进行API调用。

At the time that the child is mounted to the DOM, the parent hasn't set your state variable with the updated value, ie it's still null from your constructor. 在将子级安装到DOM时,父级尚未使用更新后的值设置状态变量,即,构造函数中的状态变量仍为null。

Placing your API call into componentDidMount() will run it after the parent has mounted, and then when the call comes back and you setState , your child will re-render with the new prop. 将您的API调用放到componentDidMount()将在父级挂载后运行它,然后当调用返回并返回setState ,您的孩子将使用新的道具重新渲染。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM