const 变量在传递给另一个函数时没有及时更新

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

我正在尝试使用当前位置坐标来发出 api 请求。但是api使用的是经纬度的默认值,而不是更新后的值,从而导致请求错误。有没有办法延迟 api 请求?

RecommendContainer.jsx

function RecommendContainer() {
  const [latitude, setLatitude] = React.useState(0);
  const [longitude, setLongitude] = React.useState(0);

  React.useEffect(() => {
    navigator.geolocation.getCurrentPosition((position) => {  //Retrieve current location
      const lat = position.coords.latitude, lng = position.coords.longitude;
      setLatitude(lat);
      setLongitude(lng)
    })
  }, [])

  return (
    <div>
      <HomePageNavBar />
      <RecommendRestaurant latitude={latitude} longitude={longitude} />
    </div>
  );
}

export default RecommendContainer;

RecommendRestaurant.jsx

function RecommendRestaurant(props)
{
    const url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='
                + String(props.latitude) + ','
                + String(props.longitude)
                + '&radius=2000&type=restaurant&keyword=healthy'
                + '&key=APIkey';

    const [data,setData]=React.useState([]);
    var config = {
        method: 'get',
        dataType: 'jsonp',
        url,
        headers:{ }
    };
    const getData=()=>{
        axios(config)
        .then(function (response) {
            console.log(response.data);
            return response.data;
        })
        .then(function(jsonData) {
            setData(jsonData);
        })
        .catch(function (error) {
            console.log(error);
        });
    }
    React.useEffect(()=>{
    getData()
    },[])


    return(
        <div className="recommend">
            <h1 style={{fontSize: 40}}>Nearby Restaurants</h1>
            <p>{props.latitude}</p>
            <p>{props.longitude}</p>
            
        </div>
    )
}
export default RecommendRestaurant;
reactjs google-places-api
1个回答
0
投票

这是更新的代码.. https://codesandbox.io/s/cocky-carson-gcsxux?file=/src/App.js [更新代码]

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