ReactJS将数据传递给子级

时间:2015-10-24 10:42:51

标签: reactjs

我有两个组件BookInfo和AuthorLink。我想从服务器获取书籍信息及其作者ID,并将其传递给AuthorLink,以便在componentDidMount中使用以获取作者姓名。但是,AuthorLink的componentDidMount在BookInfo的componentDidMount之前运行,因此authorid在传递给AuthorLink时为null。

如何在将数据传递给孩子之前获取数据并准备好数据?

var BookInfo = React.createClass({
  .
  .
  .
  componentDidMount: function() {
      var id = this.props.params.id;

      $.ajax({
        url: '/api/books/' + id,
        dataType: 'json',
        success: function(data) {
          this.setState({data: data});
        }.bind(this),
        error: function(xhr, status, err) {
          console.error('#GET Error', status, err.toString());
        }.bind(this)
      });   
  },

  render: function() {  
    return (      
      <AuthorLink authorid={this.state.data.authorid} />
    );
  } 

});


var AuthorLink = React.createClass({
  .
  .
  .
  componentDidMount: function() {
      $.ajax({
        url: '/api/author/' + this.props.authorid,
        dataType: 'json',
        success: function(data) {
          this.setState({authorname:data.authorname});
        }.bind(this),
        error: function(xhr, status, err) {          
          console.log('#GET Error', status, err.toString());
        }.bind(this)
      });      
    }
  },

  render: function() {
    return (
      <a href='#' onClick={this.linkOnClick} >
        {this.state.authorname}
      </a>
    );
  }
});

2 个答案:

答案 0 :(得分:0)

您必须将ajax来电转移到componentWillUpdatecomponentWillReceiveProps并在this.props.autherid更改时(从null更改为实际值)< / p>

或者,如果设置了<AuthorLink/>,您可以通过检查渲染来延迟this.state.authorname本身的呈现:

render: function() {

    var content = <div/>;

    if(!!this.state.authorname) {
        content =  <a href='#' onClick={this.linkOnClick} >
                       {this.state.authorname}
                   </a>;

    return content;
}

答案 1 :(得分:0)

componentDidMount在初始渲染时每个组件只运行一次,因此当我们必须等待BookInfo组件中的authorID时,它不会在这种情况下工作。

最好在AuthorLink组件中使用componentWillReceiveProps来获取作者数据,这在渲染之前运行,显然,组件中会收到新的道具。一个提示是处理渲染函数中未设置authorname的情况,这很可能是第一次渲染时的情况。

有关生命周期方法的更多信息,请:https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops