How to use fetch correctly?

六眼飞鱼酱① 提交于 2020-01-14 12:10:10

问题


I'm working on my application now. I'm trying to use fetch for login page, but I don't really understand how to use fetch even reading some example of code. Could anyone please help me get that?

For instance, I have to use these information to login to my server. username: "user" password: "1234"

then I want server return that login success or not and return a token if loging in is success

I tried to used this code

render() {
return (
  fetch('mysite', {
    method: 'POST',
    body: JSON.stringify({
      username: "user",
      password: "1234",
    })
  })
  .then((response) => response.json())
  .then((responseJson) => { return responseJson.success; })
  .catch((error) => {
    console.error(error); })
);
}

I don't know how to return success and token information. Is there are a header of this fetch? Actually I don't know that how to place this code. Is that true to use this in return of render section?

Thank you for recommendation.


回答1:


You should not call the fetch function within your render() function, this render function will be called when an update caused by changes to props or state occurs. If you do in your way, the fetch request will be called many times, again and again. The correct workflow is as below:

Therefore you should keep your fetch result into a state, then render that state in render function, pseudo code like this:

doFetch() {
fetch('mysite', {
  ...
  })
})
.then((response) => response.json())
.then((responseJson) => { 
    this.setState({someData: responseJson.success});  //***** put the result -> state
    })
.catch((error) => {
  console.error(error); })
  );
}

render () {
   {/* whatever you would like to show for someData */}
   <Text< {this.state.someData} </Text>   
   }
}



回答2:


The initial response from the fetch request is a 'Response' object, see: https://developer.mozilla.org/en-US/docs/Web/API/Response, perhaps you're interested in the Response.headers, Response.ok, Response.status or Response.statusText fields??

You can access the fields of the response in your first .then callback function. In your example you are just calling 'response.json()' which returns another promise that when resolved in the second .then callback this will result in the object parsed from the JSON response body from the response object. In your example, you are returning a 'success' property from the JSON object, is this expected in the JSON response?

MDN has some good examples of using fetch here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch



来源:https://stackoverflow.com/questions/45184450/how-to-use-fetch-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!