TypeError:undefined不是一个函数('..._ this.setState ...')

问题描述 投票:0回答:2

我是React Native的初学者(通常是编程人员),目前正在尝试使用Google Maps API的简单位置组件。当我试图获取要用于“地图”视图的位置坐标时,我陷入了以下错误。

TypeError:未定义不是函数('..._ this.setState ...')

我的代码:

import Geolocation from '@react-native-community/geolocation';
import { StyleSheet, Text, View } from 'react-native';
import FetchLocation from './components/FetchLocation';
import UsersMap from './components/UsersMap';

export default function App() {
  state = {
    userLocation: null
  }

  getUserLocationHandler=()=> {
    console.log('Pressed the button');
    Geolocation.getCurrentPosition(position =>{
      console.log(position);
      this.setState({
        userLocation:{
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          latitudeDelta: 0.2922,
          longitudeDelta: 0.2421
        }
      })

    });
  }

  return (
    <View style={styles.container}>
      <FetchLocation onGetLocation={this.getUserLocationHandler}/>
      <UsersMap userLocation={this.state.userLocation}/>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

任何帮助我发现问题的想法都会受到赞赏。

reactjs react-native react-native-ios
2个回答
0
投票

.setState仅适用于基于类的组件。您的组件正常运行。查看React Hooks,特别是useState钩子,以了解如何在功能组件中具有状态。


0
投票

为了在功能组件中包含state,您需要使用Hooks API。实现state以及setState方法的方式是类组件所独有的。请参阅official docs

有关说明,this关键字也永远不会在功能组件中起作用。

© www.soinside.com 2019 - 2024. All rights reserved.