反应状态最新更新

时间:2019-06-24 16:47:16

标签: reactjs

我需要开发一个简单的标记系统。我执行以下操作: -在img点击,我保存点击位置 -接下来我打开输入文字 -在输入更改时,我使用axios查询数据库 -依此类推,直到数据库插入标签info

问题是我更新的状态似乎是过去的1转


    imgSetTag(event){

        this.getTagPosition(event)
            .then( (response) => {              
                this.setState({
                    'imgTagsCoord' : response
                }, console.log( 'imgTagsCoord then', this.state.imgTagsCoord ));  

                document.getElementById("imgTagInput").focus();

            })
            .catch( (err) => console.log(err) )

    };

    getTagPosition(event){

        return new Promise(function(resolve, reject) {

            var bounds = event.target.getBoundingClientRect();
            var x = event.clientX - bounds.left;
            var y = event.clientY - bounds.top;
            console.log( {x: x, y: y} );

            var tagCoord = { x : Math.round( x/bounds.width * 100 ), y : Math.round( y/bounds.height * 100 ) };

            resolve(tagCoord);

        });


    }

最后一次尝试是将函数分为两部分,然后将第二部分包装在promise中,但是this.state.imgTagsCoord总是在过去。

2 个答案:

答案 0 :(得分:0)

尝试将您的setState更改为此:

 this.setState({'imgTagsCoord' : response}, () => console.log( 'imgTagsCoord then', this.state.imgTagsCoord ));  

您正在直接执行setState回调,您没有提供一个一旦状态被设置就将被React调用的函数,而是您直接在记录日志。 setState回调是React将执行的函数,在您的代码中,您将给出console.log执行的结果

答案 1 :(得分:0)

setState函数的第二个参数应为callback function。在您的情况下,应这样写:

() => console.log('imgTagsCoord then', this.state.imgTagsCoord )

直接传递console.log('imgTagsCoord then', this.state.imgTagsCoord )(而不是将其包装在匿名函数中)时,您传递的是函数的 result 而不是函数本身。因此,您将在函数执行时获得状态值,该状态值比您期望的值早一轮。

相关问题