更新提取请求中的函数级变量



我是获取和反应的新手.js基本上是javascript,我正在尝试在表中创建一个新行并只取回一个ID(然后第二个(,问题是当时域中的temp正在更改,但它在它之外没有改变,尽管我将其定义为函数级变量

handleAddRow({ newRowIndex }) {
var temp = null;
/////////////////////////////////////// updating records in db
fetch(`${config.serverUrl}/criteriaAPI`,
{
method: "POST",
dataType: 'json',
headers: {
'Accept': 'application/json; charset=UTF-8',
'Content-Type': 'application/json; charset=UTF-8'
}
})
.then(function(res){ return res.json(); })
.then(function(data){  temp = data._id ;alert(temp)})
//////////////////////////////////////
console.log(temp);
const newRow = {
_id: temp,
criteria_id: '',
securityCriteria: '',
description: '',
};
let rows = this.state.rows.slice();
rows = update(rows, {$push: [newRow]});
},

console.log(temp) = > null
alert(temp) = > id key : id value

看起来问题是您在没有等待之前的承诺完成的情况下调用console.log(temp),也就是说执行尚未达到将值分配给临时变量的地步。因此,temp 变量的值确实会发生变化 - 但它发生在执行console.log(temp)一段时间后。

如果要使用 temp 变量并且它以异步方式填充 - 则必须在相应的then处理程序中访问它。

通过将获取请求分成单个函数来解决,问题如上所述,获取请求花费了太多时间,所以我有另一个函数handleAddRow()使用 promise 等待它

addRow(){
return fetch(`${config.serverUrl}/criteriaAPI`,
{
method: "POST",
dataType: 'json',
headers: {
'Accept': 'application/json; charset=UTF-8',
'Content-Type': 'application/json; charset=UTF-8',
}
}) 
.then(response => {
return response.json()
})
.catch(err => {
console.log("fetch error" + err);
});
},

handleAddRow({ newRowIndex }) {
this.addRow()
.then(data => {  
let row =  this.createSingleRow(data);
console.log(row);
let rows = this.state.rows.slice();
rows = update(rows, {$push: row});
console.log(rows);
this.setState({ rows });
});
},
createSingleRow(data) {
console.log('Entered into createRows');
let temp = [];
temp.push({
_id: data._id,
criteria_id: data.criteria_id,
securityCriteria: data.securityCriteria,
description: data.description
});
//console.log(temp);
return temp;
},

最新更新