在反应本机应用程序中使用 Hooks 将数据传递到不同页面的最佳方法?

best way to pass data to different Pages using Hooks in a react native app?

我有一个简单的 RN 应用程序可以获取我的当前位置:

import Geolocation from '@react-native-community/geolocation';

使用 useEffect,我启动了一个名为 requestLocationPermission 的方法来检查权限,然后获取我的当前位置。

useEffect(() => {
    // console.log('is this working');
    requestLocationPermission();
  }, []);


async function requestLocationPermission() {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      {
        title: 'Location Permission',
        message: 'This app needs access to your location',
      },
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log('You can use the location');
      Geolocation.getCurrentPosition(
        position => {
          //  useCoordinates = position;
          console.log('hey man', position);
        },
        error => {
          // See error code charts below.
          console.log(error.code, error.message);
        },
        {enableHighAccuracy: false, timeout: 15000, maximumAge: 10000},
      );
    } else {
      console.log('Location permission denied', granted);
    }
  } catch (err) {
    console.warn(err);
  }
}

我想使用 useState 来存储位置,这样当我导航到包含 MapView 的页面时,当前 location/marker 会使用正确的坐标进行更新。

当前,包含地图的页面:

const About: () => React$Node = () => {
  return (
    <>
      <View style={styles.body}>
        <MapView
          style={styles.map}
          provider={PROVIDER_GOOGLE}
          initialRegion={{
            latitude: 47.48934444614,
            longitude: 227.004444388,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          }}
          showsCompass={true}>

          <Marker
            title={"house"}
            coordinate={{latitude: 47.48934444614, longitude: 227.004444388}}
          />
        </MapView>
      </View>
    </>
  );
};

export default About

有没有办法只使用钩子就可以做到这一点?或者我需要使用 Redux 吗?

您可以使用 context API.

创建上下文

const LocationContext = React.createContext({latitude: 0.0, longitude: 0.0});

使用提供程序包装您的父组件 -

<LocationContext.Provider value={/* value from geo location */}>
    {/* child view */}
</LocationContext.Provider>

子视图可以使用消费者获取值

 <LocationContext.Consumer>
      {({latitude, longitude}) => (
        <View> ... </View>
      )}
</LocationContext.Consumer>