【问题标题】:React Meteor Data - Component Not Re-Rendering With New Data While Using withTrackerReact Meteor Data - 使用 withTracker 时组件不使用新数据重新渲染
【发布时间】:2018-03-15 01:02:50
【问题描述】:

我正在使用 Meteor、React、react-meteor-data 和 React Router。我正在链接到一个页面并添加一个 /:id,然后我尝试使用它来查询数据库并使用返回的数据构建组件。

问题是初始查询返回一个空数组。然后,我可以在我的渲染方法和 componentWillReceiveProps 中看到它稍后会返回我期望的数据。问题是我的组件没有重新渲染。我使用 withTracker 是因为我希望每次目标 Collection 中的数据库发生更改时组件都更新并重新渲染。

这是客户端的 React 代码:

export default withTracker((props) => {
    const handle = Meteor.subscribe('game', props.match.params.id);
    return {
        listLoading: !handle.ready(),
        game: ActiveGames.find({ _id: props.match.params.id}).fetch(),
    };
})(Game);       

这里是 'imports/api/activeGames.js' 中的出版物:

import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { check } from 'meteor/check';

export const ActiveGames = new Mongo.Collection('activeGames');

if (Meteor.isServer) {
   Meteor.publish('game', function (id) {
      check(id, String);
      return ActiveGames.find({ _id: id });
   });

   Meteor.publish('activeGames', function activeGamesPublication() {
      return ActiveGames.find();
   });
}

这是我得到的输出的屏幕截图,其中包含用于跟踪相关生命周期方法的控制台日志。

【问题讨论】:

    标签: javascript mongodb reactjs meteor react-router


    【解决方案1】:

    我相信使用 listLoading 道具做一些事情很简单。 例如,您的 Game 组件可能是:

    class Game extends Component {
      constructor(props){
        super(props);
      }
    
      renderGames = () => {
        return this.props.games.map(g => {
          return (
            <li>{g.title}</li>
          )
        })
      }
    
      render() {
        return (
          <ul>
            {this.props.listLoading ? <span>Loading...</span> : this.renderGames()}
          </ul>
        );
      }
    }
    
    export default withTracker((props) => {
        const handle = Meteor.subscribe('game', props.match.params.id);
        return {
            listLoading: !handle.ready(),
            game: ActiveGames.find({ _id: props.match.params.id}).fetch(),
        };
    })(Game);
    

    这就是我处理订阅和接收数据之间的时间的方式。

    希望它有所帮助,尽管我确信您现在已经找到了解决方案;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 2018-08-12
      相关资源
      最近更新 更多