使用Tracker进行react-native-meteor不必要的每秒重复订阅

时间:2019-02-23 05:04:46

标签: react-native meteor

下面的屏幕/组件工作正常,但是console.log语句(withTracker部分内文件的末尾)每秒重复一次(永远),指示订阅无缘无故地反复运行-我知道由于我是唯一登录该应用程序的用户,因此服务器/数据库上的数据没有更改。

import React, { Component } from "react";
import { View, Text } from "react-native";
import { Button } from "native-base";
import Meteor, { withTracker } from "react-native-meteor";
import moment from "moment";
import LoadingScreen from "../components/LoadingScreen";

class JobDetailsScreen extends Component {
  constructor(props) {
    super(props);
    posterInfo = this.props.navigation.state.params.posterInfo;
    this.state = {
      posterUsername: posterInfo.firstName + " " + posterInfo.surname.charAt(0),
      posterProfilePicUrl: posterInfo.profilePicUrl
    };
  }

  render() {
    if (!this.props.myShiftRequestReady) {
      return <LoadingScreen />;
    }
    const job = this.props.job;
    return (
      <View>
        <H3>{job.type + ": $" + job.ratePerHour + "/hr"}</H3>
        <Image source={{uri: this.state.posterProfilePicUrl}}/>
        <Text>
          {this.state.posterUsername + moment(job.datePosted).fromNow()}
        </Text>
        <Text>{job.location}</Text>
        <Text>
          {moment(job.start).fromNow()
            + moment(job.end).from(moment(job.start), true)}
        </Text>
        <Text> {moment(job.start).format("DD/MM/YY h:mm a")
          + moment(job.end).format("DD/MM/YY h:mm a")} </Text>
        <Text>{job.summary}</Text>
        <Button
          onPress={() => {
            if (!this.props.myShiftRequest) {
              Meteor.call("ShiftRequests.add", job, (err, res) => {});
              return;
            }

            if (!this.props.myShiftRequest.accepted) {
              Meteor.call("ShiftRequests.remove", job._id, (err, res) => {});
            }
          }}
        >
          <Text>
            {!this.props.myShiftRequest
              ? "Request shift"
              : !this.props.myShiftRequest.accepted
                ? "Cancel Request"
                : this.props.myShiftRequest.didNotTurnUp
                  ? "You did not turn up for this shift"
                  : job.finshed
                    ? "Rate employer"
                    : "Shift in progress"}
          </Text>
        </Button>     
      </View>
    );
  }
}

const container = withTracker(params => {
  const jobId = params.navigation.state.params.jobId;
  const srHandle = Meteor.subscribe("myShiftRequestForJob", jobId);
  console.log("subscribing myShiftRequestForJob with jobId " + jobId);

  return {
    myShiftRequestReady: srHandle.ready(),
    myShiftRequest: Meteor.collection("shift_requests").findOne({
      userId: Meteor.userId(),
      jobId: jobId
    }),
    job: Meteor.collection("jobs").findOne({ _id: jobId })
  };
})(JobDetailsScreen);

export default container;

1 个答案:

答案 0 :(得分:0)

我最终将订阅移出了withTracker。实际上-我认为https://github.com/inProgress-team/react-native-meteor中的文档示例在演示此方法时是错误的,因为它可能导致订阅的无限循环:

  1. 订阅的数据更改,导致withTracker代码重新运行
  2. 但是在withTracker中,我们再次订阅!导致电抗值发生变化(可能)
  3. 无限循环在后台,消耗网络以及内存和CPU资源

正确的方法是订阅componentDidMount()中的数据,如本文所建议:https://daveceddia.com/where-fetch-data-componentwillmount-vs-componentdidmount/

修改后的代码:

import React, { Component } from "react";
import { View } from "react-native";
import Meteor, { withTracker } from "react-native-meteor";
import LoadingScreen from "../components/LoadingScreen";

class JobDetailsScreen extends Component {
  constructor(props) {
    super(props);
    posterInfo = this.props.navigation.state.params.posterInfo;
    this.state = {
      posterUsername: posterInfo.firstName + " " + posterInfo.surname.charAt(0),
      posterProfilePicUrl: posterInfo.profilePicUrl
    };
  }

  render() {
    if (!this.props.myShiftRequest || !this.props.job) {
      return <LoadingScreen />;
    }
    return (
      <View>
       ...
       <ComponentToDisplay/>
       ...
      </View>
    );
  }

  componentDidMount() {
    const jobId = this.props.navigation.state.params.jobId;

    const srHandle = Meteor.subscribe("myShiftRequestForJob", jobId);
    __DEV__
      ? console.log("subscribing myShiftRequestForJob with jobId " + jobId)
      : null;
  }
}

const container = withTracker(params => {
  const jobId = params.navigation.state.params.jobId;

  return {
    myShiftRequest: Meteor.collection("shift_requests").findOne({
      userId: Meteor.userId(),
      jobId: jobId
    }),
    job: Meteor.collection("jobs").findOne({ _id: jobId })
  };
})(JobDetailsScreen);

container.navigationOptions = {
  title: "Shift details"
};

export default container;