reactjs - 函数回调中的 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)
})
但变量仍然没有改变..
解决方案
你的回调中有一层额外的箭头函数。删除该行(results) => {
和匹配的}
. 如所写,逻辑是“如果状态正常,则生成一个函数但不对其执行任何操作”。您已经可以访问results
外部函数的第一个参数。
推荐阅读
- pandas - 基于日期熊猫数据框的子集
- javascript - 处理jQuery数据表中的小数
- excel - 根据数据范围 2 中的值对数据范围 1 应用条件格式
- azure - 从触发 blob 触发 Azure 函数的文件中获取元数据
- java - 错误应为 BEGIN_OBJECT,但在第 1 行第 2 列路径为 BEGIN_ARRAY
- linux - 将文件所有权更改为 root 但原始用户仍然可以编辑文件?
- java - JPA Hibernate Spring Data如何在不重新部署所有项目的情况下测试查询
- niftynet - 不知道如何生成采样位置:
- go - gorilla cookie 会话是否会持续服务器重建?
- java - maven deploy 上传旧版本和当前版本