【发布时间】:2020-12-01 06:07:29
【问题描述】:
我认为这是一个简单的语法问题,但也许这是一个更大的概念,我不了解层次结构和继承。
我正在用 react native (expo) 创建一个应用程序。我想显示一张以用户为中心且持续更新的地图(我最终将使用 watchCurrentPositionAsync,但由于我是新手,我只想尝试收集一次位置信息,然后从那里弄清楚)。当输入纬度和经度的原始值时,下面的代码成功显示了地图,但我似乎无法从状态对象中提取值以在 render() 中使用。
标有//RIGHT HERE 的行是我想使用保存在我的状态对象中的纬度/经度值的地方 - 现在我将它们设置为常量,以便我的应用程序运行。
我尝试将这些常量替换为:
this.state.initLat_s
this.state[initLat_s]
我尝试创建另一个结构“regData”并引用它的多种方式,包括引用它以获取 initialRegion 的所有信息,包括增量
我在状态内外都创建了“get()”函数,这会引发错误
我尝试使用正确的值创建“全局”变量(例如 lat_g)并使用 this.lat_g、lat_g 和许多其他语法来引用它们,但我根本无法让编译器理解对渲染中的状态变量。
export default class App extends React.Component {
state = { //state set
locationResult: null, //location result holds either location object converted to string or error message as string
locationStatus: null, //holds success status of location grab
initLat_s: null, //holds initial latitude and longitude of user location
initLon_s: null
};
componentDidMount() {this._getLocationAsync();} //if component mounts, run location grabber
_getLocationAsync = async () => { //location grabber
let { status } = await Permissions.askAsync(Permissions.LOCATION); //ask for location perms
if (status !== "granted") { //if location perms denied, set locationResult accordingly
this.setState({locationResult: "Permission to access location was denied"});
this.setState({locationStatus: false});
} else {
let initLocation = await Location.getCurrentPositionAsync({}); //otherwise, save location object in "location" var
this.setState({locationResult: JSON.stringify(initLocation)}); //set locationResult to string representation of location
this.setState({locationStatus: true});
let {initLat, initLon} = initLocation.coords; //gather lat/lon from location object
this.setState({initLat_s: initLat}); //set lat/lon in state accordingly
this.setState({initLon_s: initLon});
}
};
render() {
return (
<View style={styles.container}>
<MapView
style={styles.mapStyle}
initialRegion={{
latitude: -30, //RIGHT HERE
longitude: 120, //RIGHT HERE
latitudeDelta: .01,
longitudeDelta: .01
}}
/>
</View>
);
}
}
【问题讨论】:
-
-
不,这是我尝试的第一件事,因为我认为这是 JavaScript 的正确语法,但它似乎不起作用:/ 它在 expo 中给出“Unexpected keyword 'this'”,并且在 VSCode 中,它从编译器给出“:预期”
标签: javascript reactjs react-native maps expo