问题
I'm testing that my express server is running in React Native by calling a simple helper function in my component.
This is the helper function:
//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);
});
}
I have tried calling it like this:
<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.
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!
Thanks!
回答1:
That's because you invoked it immediately in the template.
Replace
<Button title="Test Fetch" onPress={this.testFetch('Here I am')} />
To
<Button title="Test Fetch" onPress={() => this.testFetch('Here I am')} />
Read more about it here https://reactjs.org/docs/faq-functions.html
来源:https://stackoverflow.com/questions/52588132/helper-function-with-argument-called-before-component-mount-in-react-native