处理来自.then外部.then的数据的最佳方式是什么



我正在使用谷歌的地理编码api将地址转换为坐标。

我有以下的获取来实现这一点。

fetch(
`https://maps.googleapis.com/maps/api/geocode/json?address=${prop.address}&key=${
getEnv().APP_PUBLIC_GOOGLE_API_KEY
}`
)
.then((response) => response.json())
.then((data) => console.log(data.results[0].geometry.location));

这个控制台成功地记录了我想从这个json中提取的对象。

我想知道的是:如何在代码的其余部分中使用这个对象?

对于上下文,此代码位于反应组件中

上下文

我想使用我在<GoogleMap/>组件的中心道具和<Marker/>组件的位置道具内得到的坐标对象。

您可以使用钩子useState来存储数据,useEffect来对其进行操作

function MyComponent(props) {
[ data, setData ] = useState(null);

let fetchData = () => {
fetch(
`https://maps.googleapis.com/maps/api/geocode/json?address=${props.address}&key=${
getEnv().APP_PUBLIC_GOOGLE_API_KEY
}`
)
.then((response) => response.json())
.then((data) => setData(data));
};

useEffect(() => {
if (data === null) return;

// do stuff with `data`
console.log(data.results[0].geometry.location)
}, [data]);

// rest of your component
}

快速回答:你不能。

所以也许有一个变通办法?

这是:

(async function(){
let response = await fetch(
`https://maps.googleapis.com/maps/api/geocode/json?address=${prop.address}&key=${
getEnv().APP_PUBLIC_GOOGLE_API_KEY
}`
)
response = await response.json()
//and then you can use response in the rest of your code I mean inside of the async function. If you are using node.js, and import node-fetch, then you can just do it without the async function. 
})()

最新更新