javascript - 为什么在 react native 中自动调用 setInterval

标签 javascript reactjs react-native

我正在尝试制作一个简单的时钟,它可以在按下按钮时启动和停止。在这里,我设置了一个等于 setInterval 的变量,以便稍后清除它。但是由于某种原因,它在没有按下按钮的情况下被调用。

这里 autoInc 应该在我按下“开始”按钮时被理想地调用,但它无论如何都会被调用。

import React, { Component } from "react";
import { Text, View, Button } from "react-native";

export default class Counter extends Component {
  increaser = () => {
    this.setState(prePre => {
      return { counter: prePre.counter + 1 };
    });
  };

  constructor(props) {
    super(props);

    this.state = {
      counter: 0,
      wantToShow: true
    };
    autoInc = setInterval(this.increaser, 1000);
  }

  render() {
    if (this.state.wantToShow)
      return (
        <View>
          <Text style={{ color: "red", fontSize: 50, textAlign: "center" }}>
            {this.state.counter}
          </Text>
          <Button title="Start" onPress={this.autoInc} />
        </View>
      );
  }
}

最佳答案

这里有一个完整的 react 示例,您只需在 react native 中翻译函数即可。

在你的构造函数中创建一个变量 this.interval=null ,在 startFn 中给它分配间隔,然后用 window.clearInterval( this.interval);

export default class App extends Component {
  constructor(props) {
    super(props);
    this.interval = null;
  }

  componentDidMount() {}

  startFn = () => {
    console.log("assign and start the interval");
    this.interval = setInterval(this.callbackFn, 1000);
  };

  stopFn = () => {
    console.log("clear interval");
    window.clearInterval(this.interval);
  };

  callbackFn = () => {
    console.log("interval callback function");
  };

  render(props, { results = [] }) {
    return (
      <div>
        <h1>Example</h1>
        <button onClick={this.startFn}>start Interval</button>
        <button onClick={this.stopFn}>stop Interval</button>
      </div>
    );
  }
}

此处的 Codesandbox 示例:https://codesandbox.io/s/j737qj23r5

关于javascript - 为什么在 react native 中自动调用 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53150168/

相关文章:

react-native - 如何在 TensorflowJs 中将张量解码为 Base64?

javascript - 使用 JavaScript 在请求之间传递一次性值的最佳方式

javascript - Backbone.js 设置导致集合中的模型再次成为 "initialize"

reactjs - 单元测试 - 使用 Jest 和 Enzyme 在 React 中链接

reactjs - React Router V4 交换机 vs div?

react-native - 简单的 react native 应用程序(使用 react native 导航)在闪屏后崩溃

javascript - 在操作调度时向对象数组中的每个对象添加关键属性

javascript - ReactJS 中 undefined variable

Javascript-用charAt一个字母+一个字母等显示单词

javascript - 检查样式化组件中的组件属性