如何正确使用fetch?

luf*_*oss 4 login fetch reactjs react-native fetch-api

我现在正在处理我的申请。我正在尝试将 fetch 用于登录页面,但即使阅读一些代码示例,我也不太了解如何使用 fetch。任何人都可以帮我得到吗?

例如,我必须使用这些信息登录到我的服务器。用户名:“用户” 密码:“1234”

然后我希望服务器返回登录成功与否,如果登录成功则返回一个令牌

我尝试使用此代码

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); })
);
}
Run Code Online (Sandbox Code Playgroud)

我不知道如何返回成功和令牌信息。是否有此提取的标题?其实我不知道如何放置这段代码。使用它来回报渲染部分是真的吗?

谢谢推荐。

Dav*_*vid 5

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

在此处输入图片说明

因此,您应该将 fetch 结果保持为一个状态,然后在渲染函数中渲染该状态,伪代码如下:

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>   
   }
}
Run Code Online (Sandbox Code Playgroud)