反应+流星。生成异步状态取决于集合

时间:2015-09-18 01:16:09

标签: asynchronous meteor reactjs

我在Meteor中有React组件。它需要从getMeteorData()收集。然后它从这个集合中获取ID。使用id,它必须通过异步函数获取其他信息。必须呈现此附加信息。但我不知道编码这个。

我认为代码解释得更多。所以,我想要的是:

Component = React.createClass({
  mixins: [ReactMeteorData],

  getMeteorData(){
    var handle = Meteor.subscribe("Players");
    var player = Players.findOne(this.props.playerId);
    return {
      ready: handle.ready(),
      playerBasicInfo: player
    }
  },

  getAsyncStateDependedOnData(cb){
    if (!this.data.ready)
      cb({playerAdditionalInfo: null});
    else
      asyncGetPlayerAdditionalInfo(this.data.playerBasicInfo.id, function(result) {
        cb({playerAdditionalInfo: result});
      });
  },

  render(){
    if (!this.data.ready || !this.state.playerAdditionalInfo)
      return <h1>Loading...</h1>;

    return (
      <div>
        <b>First name:</b> {this.state.playerAdditionalInfo.fname}<br/>
        <b>Last name:</b> {this.state.playerAdditionalInfo.lname}<br/>
        <b>Age:</b> {this.state.playerAdditionalInfo.age}
      </div>
    );

  }
});

如何制作 getAsyncStateDependedOnData 功能?

1 个答案:

答案 0 :(得分:1)

所以我再次回答自己。解决方案是使用父组件,它将获得流星数据,并将我们的组件渲染为包含就绪流星数据的道具的子组件。问题示例的解决方案是(使用箭头函数):

Component = React.createClass({
  mixins: [ReactMeteorData],

  getMeteorData(){
    var handle = Meteor.subscribe("Players");
    var player = Players.findOne(this.props.playerId);
    return {
      ready: handle.ready(),
      playerBasicInfo: player
    }
  },

  render(){
    if (!this.data.ready)
      return <h1>Loading...</h1>;
    return <_Component playerBasicInfo={this.data.playerBasicInfo}>;
  }
});

_Component = React.createClass({
  getInitialState(){
    return {
      playerAdditionalInfo: null
    }
  },

  getPlayerAdditionalInfo(playerBasicInfo){
    this.setState({playerAdditionalInfo: null}, () => {
      asyncGetPlayerAdditionalInfo(playerBasicInfo.id, (result) => {
        this.setState({playerAdditionalInfo: result});
      });
    });
  },

  componentDidMount(){
      this.getPlayerAdditionalInfo(this.props.playerBasicInfo);
  },
  componentWillRecieveProps(newProps){
    this.getPlayerAdditionalInfo(newProps.playerBasicInfo);
  },

  render(){
    if (!this.state.playerAdditionalInfo)
      return <h1>Loading...</h1>;
    return (
      <div>
        <b>First name:</b> {this.state.playerAdditionalInfo.fname}<br/>
        <b>Last name:</b> {this.state.playerAdditionalInfo.lname}<br/>
        <b>Age:</b> {this.state.playerAdditionalInfo.age}
      </div>
    );
  }
});

我希望代码没有任何错误,因为我没有检查它