React Native 当使用上下文挂钩将值传递给组件时,我得到了未定义的值

dzhpxtsq  于 2022-11-25  发布在  React
关注(0)|答案(1)|浏览(174)

我正在开发一个React Native应用程序,它将使用expo和context钩子在组件之间传递值。问题是,当我在context中引入MapView并在我的map组件中使用值时,不幸的是,我得到了undefined is not an object(evaluating "usePlaceContext.userLocation")。我尝试在map中使用它。jsx正在工作。我不知道我在哪里做错了。有人能帮助我解释这个问题吗?谢谢。

    • 位置上下文. jsx:**
import { createContext, useContext, useState, useEffect } from "react";
import axios from "axios";
import MapView, { Marker } from "react-native-maps";
import * as Location from "expo-location";

const PlaceContext = createContext();

export const ContextProvider = ({ children }) => {
  const [places, setPlaces] = useState([]);
  const [filterPlaces, setFilterPlaces] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);
  const [searchValue, setSearchValue] = useState("");
  const [locality, setLocality] = useState({
    latitude: 37.78825,
    longitude: 11.50078,
    latitudeDelta: 0.0922,
    longitudeDelta: 0.0421,
  });

  useEffect(() => {
    axios
      .post(
        "https://where2playdk.herokuapp.com/nearest?lat=55.70232019168349&lon=12.561693791177802"
      )
      .then((response) => setPlaces(response.data))
      .catch((error) => setIsError(error))
      .finally(() => setIsLoading(true));
  }, []);

  const userLocation = async () => {
    let { status } = await Location.requestForegroundPermissionsAsync();
    if (status !== "granted") {
      setErrorMsg("Permission denied");
    }
    let location = await Location.getCurrentPositionAsync({
      enableHighAccuracy: true,
    });
    setLocality({
      latitude: location.coords.latitude,
      longitude: location.coords.longitude,
      latitudeDelta: 0.0922,
      longitudeDelta: 0.0421,
    });

    console.log(
      `my location:${(location.coords.latitude, location.coords.longitude)}`
    );
  };

  return (
    <PlaceContext.Provider
      value={{
        places,
        isLoading,
        isError,
        setSearchValue,
        searchValue,
        locality,
        userLocation,
      }}
    >
      {children}
    </PlaceContext.Provider>
  );
};

export const usePlaceContext = () => useContext(PlaceContext);
    • 主屏幕. jsx:**
import {
  StyleSheet,
  ImageBackground,
  SafeAreaView,
  View,
  Text,
} from "react-native";
import { StatusBar } from "expo-status-bar";
import Search from "../../components/search/Search";
import AppLogo from "../../components/appLogo/AppLogo";
import PlayGrounds from "../../components/places/PlayGrounds";
import backgroundImage from "../../../assets/images/imageBG.jpeg";
import { ContextProvider } from "../../context/placeContext";
import { colors } from "../../../assets/theme/theme";

const HomeScreen = () => {
  return (
    <ImageBackground source={backgroundImage} style={styles.container}>
      <ContextProvider>
        <PlayGrounds
          ListHeaderComponent={() => (
            <SafeAreaView style={styles.frame}>
              <AppLogo />
              <Search />
              <View style={styles.locationContainer}>
                <Text style={styles.myLocation}>I here</Text>
              </View>
            </SafeAreaView>
          )}
        />
        <StatusBar style="default" />
      </ContextProvider>
    </ImageBackground>
  );
};

export default HomeScreen;
    • Map. jsx:**
import React, { useState, useEffect } from "react";
import {
  StyleSheet,
  View,
  TextInput,
  Dimensions,
  SafeAreaView,
} from "react-native";
import { colors } from "../../../assets/theme/theme";
import MapView, { Marker } from "react-native-maps";
import { usePlaceContext } from "../../context/placeContext";
import { MaterialIcons } from "@expo/vector-icons";
import SafeViewAndroid from "../../components/androidSafeAreaView/AndroidSafeAreaView";

const MapScreen = () => {
  const [searchText, setSearchText] = useState("");
  const { userLocation, locality } = usePlaceContext();

  useEffect(() => {
    userLocation();
  }, []);

  return (
    <SafeAreaView style={SafeViewAndroid.AndroidSafeArea}>
      <SafeAreaView style={styles.mapContainer}>
        <View style={styles.topItems}>
          <MaterialIcons
            style={styles.icon}
            name="my-location"
            size={20}
            color="black"
            onPress={userLocation}
          />
          <TextInput
            style={styles.input}
            onChangeText={(value) => setSearchText(value)}
            value={searchText}
            placeholder="Search a playground here..."
            placeholderTextColor={`${colors.gray}`}
          />
        </View>
        <SafeAreaView style={styles.container}>
          <MapView style={styles.map} region={locality}>
            <Marker coordinate={locality} title="Marker" />
          </MapView>
        </SafeAreaView>
      </SafeAreaView>
    </SafeAreaView>
  );
};

export default MapScreen;

xuo3flqw

xuo3flqw1#

检查Map.jsx是否不是Homescreen.jsx的子a,它可以访问ConfigProvider

相关问题