Reactjs中的getCurentPosition()不更新状态

Posted

技术标签:

【中文标题】Reactjs中的getCurentPosition()不更新状态【英文标题】:getCurentPosition() in Reactjs not updating state 【发布时间】:2020-06-16 11:50:03 【问题描述】:

我正在尝试在我的应用程序中获取用户当前位置,但即使我在 console.log 时可以看到它,它也不起作用。 我正在使用异步函数来检索它,但我一定做错了什么,我无法弄清楚问题是什么。

上下文状态

import React,  useReducer  from "react";
import RestContext from "./restContext";
import RestReducer from "./restReducer";
import Yelp from "../../Util/Yelp";
import  getCurrentPosition  from "../../Util/GeoLocation";
import 
  GET_RESTAURANTS,
  GET_INFO_RESTAURANT,
  CLEAR_SEARCH,
  SET_LOADING,
  GET_LOCATION,
 from "../../types";

const RestState = (props) => 
  const initalState = 
    restaurants: [],
    restaurant: ,
    loading: false,
    location: ,
  ;

  const [state, dispatch] = useReducer(RestReducer, initalState);

  // Get Restaurants
  const getRestaurants = async (text) => 
    setLoading();

    let restaurants = await Yelp.searchRestaurants(text);

    if (restaurants) 
      dispatch( type: GET_RESTAURANTS, payload: restaurants );
     else 
      dispatch( type: GET_RESTAURANTS, payload: [] );
    
  ;

  // Get info Restaurants

  const getRestaurantInfo = async (id) => 
    setLoading();
    let restaurant = await Yelp.searchRestaurantsInfo(id);

    if (restaurant) 
      dispatch( type: GET_INFO_RESTAURANT, payload: restaurant );
     else 
      dispatch( type: GET_INFO_RESTAURANT, payload:  );
    
  ;

  // Clear search

  const clearSearch = () => dispatch( type: CLEAR_SEARCH );

  // Set loading

  const setLoading = () => dispatch( type: SET_LOADING );

  // Get location

  const fetchCoordinates = async () => 
    try 
      const coords = await getCurrentPosition();
      dispatch( type: GET_LOCATION, payload: coords );
     catch (error) 
      // Handle error
      console.error(error);
    
  

  return (
    <RestContext.Provider
      value=
        restaurants: state.restaurants,
        restaurant: state.restaurant,
        loading: state.loading,
        getRestaurants,
        clearSearch,
        getRestaurantInfo,
        fetchCoordinates,
      
    >
      props.children
    </RestContext.Provider>
  );
;

export default RestState;

这是减速器

import 
  GET_RESTAURANTS,
  GET_INFO_RESTAURANT,
  CLEAR_SEARCH,
  SET_LOADING,
  GET_LOCATION,
 from "../../types";

export default (state, action) => 
  switch (action.type) 
    case GET_RESTAURANTS:
      return  ...state, restaurants: action.payload, loading: false ;
    case GET_INFO_RESTAURANT:
      return  ...state, restaurant: action.payload, loading: false ;
    case CLEAR_SEARCH:
      return  ...state, restaurants: [], loading: false ;
    case SET_LOADING:
      return 
        ...state,
        loading: true,
      ;
    case GET_LOCATION:
      return  ...state, location: action.payload ;
    default:
      return state;
  
;

以及应该使用的主页

import React,  Fragment, useEffect, useContext  from "react";
import Search from "../../Components/restaurants/Search";
import Alert from "../../Components/layout/Alert";
import Navbar from "../../Components/layout/Navbar";
import DisplayRestaurants from "../../Components/layout/DisplayRestaurants";
import Footer from "../../Components/layout/Footer";
import  Waypoint  from "react-waypoint";
import RestContext from "../context/restaurant/restContext";

const Home = () => 
  const restContext = useContext(RestContext);

  useEffect(() => 
    restContext.fetchCoordinates();
    // eslint-disable-next-line
  , []);

  const handleWaypointEnter = () => 
    document.querySelector("nav").classList.remove("fixed");
  ;
  const handleWaypointLeave = () => 
    document.querySelector("nav").classList.add("fixed");
  ;

  return (
    <section className="main-home">
      <Fragment>
        <Navbar />
        <Search />
        <Alert />
        <Waypoint onEnter=handleWaypointEnter onLeave=handleWaypointLeave />
        <DisplayRestaurants />
        <Footer />
      </Fragment>
    </section>
  );
;

export default Home;

获取当前位置

export function getCurrentPosition(options = ) 
  return new Promise((resolve, reject) => 
    navigator.geolocation.getCurrentPosition(resolve, reject, options);
  );

坐标对象

GeolocationCoordinates latitude: 52.3555177, longitude: -1.1743196999999999, altitude: null, accuracy: 372529, altitudeAccuracy: null, …
accuracy: 372529
altitude: null
altitudeAccuracy: null
heading: null
latitude: 52.3555177
longitude: -1.1743196999999999
speed: null
__proto__: GeolocationCoordinates

感谢您的帮助

【问题讨论】:

评论不用于扩展讨论;这个对话是moved to chat。 【参考方案1】:

你可以试试这个吗?

它返回一个承诺,所以理论上应该可以使用.then


    getCurrentPosition().then((res) => 
      console.log(res) // check what `res` is
      dispatch( type: GET_LOCATION, payload: res.cords );
    )

【讨论】:

我试过了,但它和使用异步完全一样。当我 console.log res 它给了我一个对象(我也试过typeof 以确保)在坐标内。基本上和以前一样的问题 对象是什么样子的? 我刚刚将它添加到主要问题中 我以为你解决了?也许我看错了。我现在不在,但回家后会再看看! 是的,我解决了。在您询问对象的外观之前,我将其添加到主要问题中,而不是对其进行解释。感谢您的帮助,仔细检查对我有很大帮助

以上是关于Reactjs中的getCurentPosition()不更新状态的主要内容,如果未能解决你的问题,请参考以下文章

保存状态中的对象数组 - ReactJS

ReactJS 中的“context”和“localStorage”有啥区别?

ReactJS 中的参数路由不显示 UI 组件

reactjs - 如何隐藏一个div并将其替换为reactjs中的另一个div?

ReactJS:为啥 .scss 没有正确引用 id 中的 className?

如何保护 ReactJs 中的路由?