在React Native组件安装之前调用带有参数的Helper函数 [英] Helper Function with argument called before component mount in React Native

查看:89
本文介绍了在React Native组件安装之前调用带有参数的Helper函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过在组件中调用一个简单的帮助程序功能来测试Express服务器是否在React Native中运行。

I'm testing that my express server is running in React Native by calling a simple helper function in my component.

这是辅助函数:

//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')} />

在第一种情况下,没有问题,当我按下按钮并正确运行。

In the first case, there is no problem, the component renders and the function runs when I hit the button and runs correctly.

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

However, if I send an argument, such as the second case, the helper function seems to execute before the component renders and (if my express server is not up and running) throws the error in the catch block without showing my screen.

我丢失了什么?如果我使用参数调用辅助函数,则该辅助函数似乎在安装时执行(这不是我想要的)。我正在使用模拟器,因此不确定是否有点奇怪吗?

What am I missing? The helper function seems to execute upon mounting if i call it with an argument (which is not what I want). I am using simulator so not sure if it is something odd with that?

理想情况下,当我检测到服务器不存在时,我想将屏幕更改为脱机状态。在第一种情况下,我可以在第二种情况下,一切似乎都在执行并崩溃。我知道我在这里确实缺少一些基本知识!

Ideally, I want to change my screen to an offline state when I detect the server is not there. In the first case, I can, in the second case, everything just seems to execute and crash. I know I am missing something really basic here!

谢谢!

推荐答案

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

That's because you invoked it immediately in the template.

替换

<按钮标题= Test Fetch onPress = {this.testFetch('Here I am' )} />

收件人

<按钮标题= Test Fetch onPress = {()=> this.testFetch('Here I am')} />

在此处了解更多信息 https://reactjs.org/docs/faq-functions.html

这篇关于在React Native组件安装之前调用带有参数的Helper函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆