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

Updating function level variable in a fetch request

我是新手,react.js 基本上是 javascript,我正在尝试在 table 中创建一个新行,然后只取回一个 ID(然后是第二个),问题是 then 域中的 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) 被执行后的某个时间。

如果您想使用临时变量并以异步方式填充 - 您必须在相应的 then 处理程序中访问它。

通过将提取请求分离到一个函数中解决了问题,如上所述,提取请求花费了太多时间,所以我有另一个函数 handleAddRow() 使用 promises [=12] 等待它=]

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