在 React Native 中组件挂载之前调用带有参数的辅助函数

Helper Function with argument called before component mount in React Native

我通过在我的组件中调用一个简单的辅助函数来测试我的快速服务器在 React Native 中是 运行。

这是辅助函数:

//Helper functions
  testFetch(msg) {
    console.log("Msg: ", msg);
    fetch("http://localhost:5000", {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      }
    })
      .then(response => response.json())
      .then(responseJson => {
        console.log("Express response: ", responseJson);
        this.setState({ myText: responseJson });
      })
      .catch(error => {
        console.error("ERROR: Fetch (Entry.js, testFetch) ", error.message);
      });
  }

我试过这样称呼它:

<Button title="Test Fetch" onPress={this.testFetch} />
<Button title="Test Fetch" onPress={this.testFetch('Here I am')} />

在第一种情况下,没有问题,当我按下按钮并正确运行时,组件呈现并且函数运行。

但是,如果我发送一个参数,例如第二种情况,辅助函数似乎在组件呈现之前执行并且(如果我的 express 服务器未启动并且 运行)抛出错误catch 块而不显示我的屏幕。

我错过了什么?如果我用参数调用辅助函数(这不是我想要的),辅助函数似乎会在挂载时执行。我正在使用模拟器,所以不确定它是否有问题?

理想情况下,当我检测到服务器不存在时,我想将我的屏幕更改为离线状态。在第一种情况下,我可以,在第二种情况下,一切似乎都在执行和崩溃。我知道我在这里遗漏了一些非常基本的东西!

谢谢!

那是因为您在模板中立即调用了它。

替换

<Button title="Test Fetch" onPress={this.testFetch('Here I am')} />

<Button title="Test Fetch" onPress={() => this.testFetch('Here I am')} />

在此处阅读更多相关信息 https://reactjs.org/docs/faq-functions.html