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

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

问题描述

我正在处理我的应用程序.我正在尝试将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函数.如果您以自己的方式进行操作,则提取请求将被多次调用.正确的工作流程如下:

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:

因此,您应该将获取结果保持在某种状态,然后在render函数中渲染该状态,就像这样的伪代码:

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

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

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