如何使用useState钩子更新对象

时间:2020-04-01 00:51:49

标签: react-native

我需要进行状态更新并使用它。我尝试了几种方法,如果在发出请求并返回响应后打印dropOffCoordinates,即使使用.then()也不会更新状态。我尝试将setDropOffCoordinates()放在useEffect挂钩中,但无法正常工作。

import React, { useState, useEffect, useContext, useRef } from "react";
const [dropOffCoordinates, setDropOffCoordinates] = useState({
   latitude: 0,
   longitude: 0
 });
const getCoordinatesofDropoffPlace = place_id => {
    getPlaceCoordinates(place_id)
      .then(response => {
        console.log('response drop off: ', response)
        setDropOffCoordinates( dropOffCoordinates => 
          ({
            ...dropOffCoordinates,
            latitude: response.lat,
            longitude: response.lng
          })
        );
        console.log("after: ", dropOffCoordinates)
      })
      .then( () => console.log('dropOffCoordinates', dropOffCoordinates) )
      .catch(error => {
        console.log(error);
      });
  };
useEffect(
    () => {
      getCoordinatesofDropoffPlace
    }, [dropOffCoordinates]
   )

我在组件内部的可触摸不透明onPress函数中调用此函数

onPress={ () => {
    getCoordinatesofDropoffPlace(place.place_id);
}

1 个答案:

答案 0 :(得分:1)

调用setState时。 React将准备更新应用程序树,但是变量dropOffCoordinates仍然相同。我将尝试:

  1. 创建我的位置对象并使用它,并在流程结束时使用setState
getPlaceCoordinates(place_id)
      .then(response => {
        console.log('response drop off: ', response)
        console.log("component coordinates will be the same until reload", dropOffCoordinates)
        const coordinates = {
          latitude: response.lat,
          longitude: response.lng
        }

        // do your job with coordinates
        setDropOffCoordinates(coordinates)
      })
      .catch(error => {
        console.log(error);
      });
  1. 我将进行更新并对更改产生影响
const [dropOffCoordinates, setDropOffCoordinates] = React.useState({
    latitude: 0,
    longitude: 0
  });
  const getCoordinatesofDropoffPlace = place_id => {
    getPlaceCoordinates(place_id)
      .then(response => {
        console.log("response drop off: ", response);
        const newCoordinates = {
          latitude: response.lat,
          longitude: response.lng
        }
        // you can use newCorrdinates to do your job
        setDropOffCoordinates(newCoordinates);
      })
      .catch(error => {
        console.log(error);
      });
  };
  React.useEffect(() => {
    // DO HERE YOUR JOB ON UPDATE
  }, [dropOffCoordinates]);