我现在正在处理我的申请。我正在尝试使用 fetch 来登录页面,但即使阅读一些代码示例,我也不太明白如何使用 fetch 。谁能帮我解决这个问题吗?
例如,我必须使用这些信息登录我的服务器。 用户名:“用户” 密码:“1234”
然后我希望服务器返回登录成功与否,如果登录成功则返回 token
我尝试使用此代码
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); })
);
}
不知道如何返回成功和token信息。 此获取是否有 header ?其实我不知道如何放置这段代码。使用它来返回渲染部分是真的吗?
感谢您的推荐。
最佳答案
您不应在 render() 函数中调用 fetch 函数,当因 props 或 state 发生更改而导致更新时,将调用此 render 函数。如果您按照自己的方式这样做,则提取请求将被一次又一次地调用多次。正确的工作流程如下:
因此,您应该将获取结果保留为某种状态,然后在渲染函数中渲染该状态,伪代码如下:
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>
}
}
关于reactjs - 如何正确使用fetch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45184450/