如何正确使用 fetch? [英] How to use fetch correctly?

查看:35
本文介绍了如何正确使用 fetch?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在处理我的申请.我正在尝试将 fetch 用于登录页面,但即使阅读一些代码示例,我也不真正了解如何使用 fetch.有谁能帮我弄一下吗?

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?

例如,我必须使用这些信息来登录我的服务器.用户名:用户"密码:1234"

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

我尝试使用此代码

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?

感谢您的推荐.

推荐答案

你不应该在你的 render() 函数中调用 fetch 函数,这个 render 函数会在 props 或 state 发生变化时调用.如果您按照自己的方式进行操作,获取请求将被多次调用,一次又一次.正确的工作流程如下:

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>   
   }
}

这篇关于如何正确使用 fetch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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