【发布时间】:2019-10-18 06:52:13
【问题描述】:
我在使用 Node.js 和 React.js 从 fetch post 请求中保存数据时遇到问题。我正在从 React 组件类中的函数调用 fetch 请求。我想从我的数据库中查询一些用户 ID,然后将其保存到 React 组件实例变量之一,即“this.userid”但是,每当我将值分配给一个空变量时,我都会在“.then”语句之外检查它你可以看到它从未被分配。
是否有人知道执行获取请求的方法或正确方法?我正在创建一个简单的登录发布请求,并希望在从 API 返回后保存用户 ID。
class LandingPage extends React.Component {
constructor(props) {
super(props)
this.data = data
}
login(e){
var that = this;
function log(id){
that.userid = id
}
fetch("/login", {
method: "POST",
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
body: JSON.stringify(this.data)
}).then(response => {
return response.json();
})
.then(json =>log(json.userid))
/both show undefined
console.log(that.userid, this.userid)
}
【问题讨论】:
标签: reactjs asynchronous fetch