Javascript 尝试将变量传入文本组件
我想将stateName变量传入文本组件。当它位于responseJson函数内部时,我如何才能做到这一点Javascript 尝试将变量传入文本组件,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我想将stateName变量传入文本组件。当它位于responseJson函数内部时,我如何才能做到这一点 const App = () => { fetch('https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJpe7ZFZId9ocRnkR32F9xAcw&key=') .then((response) => response.json()) .then((responseJson) =>
const App = () => {
fetch('https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJpe7ZFZId9ocRnkR32F9xAcw&key=')
.then((response) => response.json())
.then((responseJson) => {
console.log('ADDRESS GEOCODE is BACK! => ' + JSON.stringify(responseJson));
const stateName = responseJson.results[0].address_components.filter((x: Object) => x.types.filter((t: Object) => t == 'administrative_area_level_1').length > 0)[0].short_name;
return (
<Text>{stateName}</Text> // ???
)
}
const-App=()=>{
取('https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJpe7ZFZId9ocRnkR32F9xAcw&key=')
.then((response)=>response.json())
.然后((responseJson)=>{
log('ADDRESS GEOCODE回来了!=>'+JSON.stringify(responseJson));
const stateName=responseJson.results[0]。地址\u组件。过滤器((x:Object)=>x.types.filter((t:Object)=>t=='administration\u area\u level\u 1')。长度>0)[0]。短\u名称;
返回(
{stateName}/???
)
}
我认为您是在last-then-block中声明stateName尝试将其设置为全局,然后在last-then-block中进行更新您需要在获取数据时更改状态,在您的情况下,只需在获取数据之前传递变量一次即可
import React, {useEffect, useState} from 'react';
import {Text} from 'react-native';
const App = () => {
const [data, setData] = useState(null)
useEffect(() => {
fetch('https://maps.googleapis.com/maps/api/geocode/json')
.then((response) => response.json())
.then((responseJson) => {
const resData = responseJson.results[0].address_components.filter((x: Object) => x.types.filter((t: Object) => t == 'administrative_area_level_1').length > 0)[0].short_name;
setData(resData);
})
}, []);
return (
<Text>{String(data)}</Text>
)
}
import React,{useffect,useState}来自“React”;
从“react native”导入{Text};
常量应用=()=>{
const[data,setData]=useState(null)
useffect(()=>{
取('https://maps.googleapis.com/maps/api/geocode/json')
.then((response)=>response.json())
.然后((responseJson)=>{
const resData=responseJson.results[0]。地址\u组件。筛选器((x:Object)=>x.types.filter((t:Object)=>t=='administration\u area\u level\u 1')。长度>0)[0]。短\u名称;
setData(resData);
})
}, []);
返回(
{字符串(数据)}
)
}
当我将var stateName;作为最后一个then块之外的全局变量添加时,它会传递到文本组件。但是,它实际上不会返回任何内容。实际结果应该是MN,这会导致console.log(stateName)谢谢!它现在可以工作了。还有一件事,您可以编辑您的回复并删除我的api密钥吗?