Reactjs 在React Native中装入组件之前调用了参数为的Helper函数
我正在测试我的express服务器是否在React Native中运行,方法是在我的组件中调用一个简单的helper函数 这是辅助函数:Reactjs 在React Native中装入组件之前调用了参数为的Helper函数,reactjs,react-native,components,offlineapps,offline-mode,Reactjs,React Native,Components,Offlineapps,Offline Mode,我正在测试我的express服务器是否在React Native中运行,方法是在我的组件中调用一个简单的helper函数 这是辅助函数: //Helper functions testFetch(msg) { console.log("Msg: ", msg); fetch("http://localhost:5000", { method: "GET", headers: { Accept: "application/json",
//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')} />
在第一种情况下,没有问题,当我按下按钮并正确运行时,组件渲染并运行函数
但是,如果我发送一个参数,例如第二种情况,则helper函数似乎在组件呈现之前执行,并且(如果我的express服务器未启动并运行)在catch块中抛出错误,而不显示我的屏幕
我错过了什么?如果我用参数调用helper函数(这不是我想要的),它似乎会在装载时执行。我正在使用模拟器,所以不确定这是不是有点奇怪
理想情况下,当我检测到服务器不在时,我希望将屏幕更改为脱机状态。在第一种情况下,我可以,在第二种情况下,一切似乎都在执行和崩溃。我知道我错过了一些非常基本的东西
谢谢 这是因为您在模板中立即调用了它 更换
至
this.testFetch(“我在这里”)}/>
请在此处阅读更多信息谢谢Chiril!-我知道我犯了一些基本的错误——在这里发布之前,我花了一上午的时间试图在代码和互联网文章中找到它。你的回答解决了问题,谢谢你的文档链接——现在我更清楚了!:)