首页 > 解决方案 > 函数回调中的 setState

问题描述

我需要在我的函数的回调中调用 setState。由于某种原因,它似乎没有被调用。在组件外调用 setState 的正确方法是什么?这是我的代码:

service.findPlaceFromQuery(request, (results, status) => {
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                (results) => {
                    console.log(this.setState())
                    this.setSate({
                        addressMarker: {
                            icon: results[0].image,
                            title: results[0].name,
                            lat: results[0].geometry.location.lat,
                            lng: results[0].geometry.location.lng
                        }
                    })
                }
            }
            else
                console.log("ERROR!: "+results)
        })

我已将代码更新如下:

service.findPlaceFromQuery(request, (results, status) => {
                if (status == google.maps.places.PlacesServiceStatus.OK) {
                        console.log(this.setState())
                        this.setSate({
                            addressMarker: {
                                icon: results[0].image,
                                title: results[0].name,
                                lat: results[0].geometry.location.lat,
                                lng: results[0].geometry.location.lng
                            }
                        })
                }
                else
                    console.log("ERROR!: "+results)
            })

但变量仍然没有改变..

标签: reactjs

解决方案


你的回调中有一层额外的箭头函数。删除该行(results) => {和匹配的}. 如所写,逻辑是“如果状态正常,则生成一个函数但不对其执行任何操作”。您已经可以访问results外部函数的第一个参数。


推荐阅读