【问题标题】:React Native: best practice to setInterval and Promises with setState in itReact Native:setInterval 和 Promises 的最佳实践,其中包含 setState
【发布时间】:2018-08-31 02:29:52
【问题描述】:

我目前正在与“无法 setState() 或 forceUpdate() 卸载组件错误”作斗争,并且很难跟踪错误来自哪个异步操作。我怀疑这是因为setInterval 我用来添加秒数来显示当前时间。这是我在componentDidMountcomponentWillUpdatecomponentWillUnmount 中负责管理时间显示的内容:

componentDidMount() {
    this.mounted = true;

    //listener to identify whether app is active/inactive
    AppState.addEventListener('change', this.handleAppStateChange.bind(this));

    //get user's intranet schedule
    this.props.actionsMain.getSchedule(this.props.staff.staffID);

    this.getLocation();
    //After the first location received, re-check every 20 seconds
    this.locationInterval = setInterval(() => {
      this.getLocation();
    }, 20000);
  }

componentDidUpdate() {
    //when we just received server time, parse and set the time to state, then set the interval timer
    if (this.props.scheduleReceived && this.state.time[0] === null) {
      let time = this.props.schedule['time_server'].split(':'),
        hh = parseInt(time[0]) + this.props.location.zone,
        mm = parseInt(time[1]),
        ss = parseInt(time[2]);

      if (this.mounted) {
        this.setState({ time: [hh, mm, ss] });

        this.serverTimeInterval = setInterval(() => {
          let { time } = this.state, hh = time[0], mm = time[1], ss = time[2];

          //add second and adjust time
          ss += 1;
          if (ss >= 60) {
            ss -= 60;
            mm += 1;

            if (mm >= 60) {
              mm -= 60;
              hh += 1;

              if (hh >= 24)
                hh -= 24;
            }
          }

          if (this.mounted)
            this.setState({ time: [hh, mm, ss] })
        }, 1000)
      }
    }
  }

componentWillUnmount() {
    //Remove all timer events
    clearInterval(this.serverTimeInterval);
    clearInterval(this.locationInterval);

    //Remove listener
    AppState.removeEventListener('change', this.handleAppStateChange.bind(this));

    this.mounted = false;
  }

任何人都可以指出我在这里做错了什么吗?即使我正在做的是一个好的做法?

同样,我的第二个怀疑来自从setInterval() 执行并返回到未安装组件的获取位置承诺。如果我可以遵循任何经验法则来确保 setInterval、setState 和 Promises 和谐地工作,那就太棒了!

提前致谢!

【问题讨论】:

    标签: javascript reactjs react-native state setinterval


    【解决方案1】:

    永远不要在componentDidUpdate中调用setState,会导致死循环

    【讨论】:

    • 我知道,由于我输入的条件,这不会导致无限循环,问题绝对不是那个,尽管这可能不是一个好习惯。那么你建议我把我现在放在componentDidUpdate 中的东西放在哪里?我需要它们在componentDidMount 之后运行,这是我现在唯一能想到的放置它们的地方..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 2020-09-17
    • 2013-03-03
    • 2016-05-02
    相关资源
    最近更新 更多