我正在尝试将纬度和经度值(使用主屏幕中的navigator.geolocation获取)发送到详细信息屏幕,但是详细信息页面接收的是空值,而不是实际值。这是我的代码:< / p>
import React from 'react';
import { View, Text, Button } from 'react-native';
import { createStackNavigator } from 'react-navigation';
class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
latitude: null,
longitude: null,
error: null,
};
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button title="Add New Outlet" onPress={() => {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
this.props.navigation.navigate('Details', {latitude: this.state.latitude, longitude: this.state.longitude,});
}}/>
</View>
);
}
}
class DetailsScreen extends React.Component {
render() {
const { navigation } = this.props;
const latitude = navigation.getParam('latitude', 'NO-ID');
const longitude = navigation.getParam('longitude', 'some default value');
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
<Text>latitude: {JSON.stringify(latitude)}</Text>
<Text>longitude: {JSON.stringify(longitude)}</Text>
</View>
);
}
}
const RootStack = createStackNavigator(
{
Home: HomeScreen,
Details: DetailsScreen,
},
{
initialRouteName: 'Home',
}
);
export default class App extends React.Component {
render() {
return <RootStack />;
}
}
这些值已成功在组件之间传递,但当前状态值未传递。请帮助...
答案 0 :(得分:0)
这可能是this.setState()
异步性质的问题。尝试稍微修改一下代码。与其在this.props.navigation.navigate()
之后调用this.setState()
,不如在回调的this.setState()
内作为第二个参数调用它。这是您的操作方法:
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
}, () => {
this.props.navigation.navigate('Details', {latitude: this.state.latitude, longitude: this.state.longitude,})
});
我希望能有所帮助。让我知道它是否有效。