简体   繁体   English

在 react.js 中使用 API 时,如何使一个使用效果先于另一个使用效果运行

[英]How do I make a use effect run before another while using an API in react.js

The purpose of this project is to dynamically get the coordinates and bounds from a map API and use its values to get the data of places attached to that area这个项目的目的是从一个 map API 动态获取坐标和边界,并使用它的值来获取附属于该区域的地方的数据

The situation I have is that on my app.js I have two use effects:我的情况是在我的 app.js 上有两个使用效果:

  • the first is to get the user's location after the window is loaded this makes it possible for the map API to work.第一个是在加载 window 后获取用户的位置,这使得 map API 可以工作。

  • the second is to get the data from a different API based on the bounds gotten from the map.第二种是根据从 map 获得的边界从不同的 API 获得数据。

    const App =() => { const [places, setPlaces]= useState([]); const App =() => { const [places, setPlaces]= useState([]); const [coordinates, setCoordinates] = useState({lat: 0, lng: 0}); const [坐标,setCoordinates] = useState({lat: 0, lng: 0}); const [bounds, setBounds]= useState(null); const [bounds, setBounds]= useState(null);

     useEffect(()=>{ let mounted = true; window.addEventListener('load', (event) => { navigator.geolocation.getCurrentPosition(({ coords: {latitude, longitude} }) => { if (mounted){ setCoordinates({ lat: latitude, lng: longitude }); } },(err)=> { console.warn(`ERROR(${err.code}): ${err.message}`); },{maximumAge:60000, timeout:5000, enableHighAccuracy:true}); console.log('page is fully loaded'); }); return ()=>{ mounted = false; } }, []); useEffect(() => { console.log(coordinates, bounds); let isApiSuscribed= true; getPlacesData(bounds.sw, bounds.ne)//I am trying to get the API data using this.then((data) => { if (isApiSuscribed){ console.log(data); setPlaces(data); } }); return ()=>{ isApiSuscribed=false; } }, [coordinates,bounds]); return( <> <CssBaseline /> <Header /> <Grid container spacing={3} style={{width:'100%'}}> <Grid item xs={12} md={4}> <List places={places}/> </Grid> <Grid item xs={12} md={8}> <Map setCoordinates={setCoordinates} setBounds = {setBounds} coordinates ={coordinates} /> </Grid> </Grid> </> ) } export default App;

The Challenge is that if I do not call the bounds.sw, bounds.ne parameters in the getPlacesData() function my Locally hosted page would run showing the appropriate Map and other components but the data that I need to fetch from the other API would not work.挑战在于,如果我不调用getPlacesData() function 中的bounds.sw, bounds.ne参数,我的本地托管页面将运行并显示相应的 Map 和其他组件,但我需要从其他 API 获取的数据将不行。

And when I then call the bounds.sw, bounds.ne parameters in the getPlacesData() function then nothing is rendered on the screen and I get the following error codes: Error Message然后,当我在getPlacesData() function 中调用bounds.sw, bounds.ne参数时,屏幕上没有任何内容呈现,我得到以下错误代码:错误消息

this is the code for the API that is to return the data back这是用于返回数据的 API 的代码

import axios from 'axios';

const URL ='https://travel-advisor.p.rapidapi.com/restaurants/list-in-boundary';



export const getPlacesData = async (sw, ne) => {
  try {
    const { data: { data } } = await axios.get(URL, {
      params: {
        bl_latitude: sw.lat,
        bl_longitude: sw.lng,
        tr_longitude: ne.lng,
        tr_latitude: ne.lat,
      },
      headers: {
        'x-rapidapi-key': process.env.REACT_APP_RAPID_API_TRAVEL_API_KEY,
        'x-rapidapi-host': 'travel-advisor.p.rapidapi.com',
      },
    });

    return data;
  } catch (error) {
    console.log(error);
  }
};

Please what do I do?请问我该怎么办?

It would be better if you could chain these operations instead of two disconnected useEffect s.如果您可以链接这些操作而不是两个断开连接的useEffect会更好。 Try calling the getPlacesData function where you're now changing the state using setCoordinates , inside the first useEffect .尝试在第一个 useEffect 中使用setCoordinates调用getPlacesData function 来更改useEffect

I would also recommend extracting this out into a custom hook to make the code cleaner.我还建议将其提取到自定义挂钩中以使代码更清晰。

As a side note, you might not actually need window.addEventListener since this component will already have mounted when the first useEffect is triggered.附带说明一下,您实际上可能不需要window.addEventListener ,因为在触发第一个 useEffect 时该组件已经挂载。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React.js如何在另一个组件中使用一个组件? - React.js How do I use a component in another component? 如何使用 Spring 引导、mongodb 和 React.js 在另一个集合中使用 collections 列表? - How can i use list of collections in another collection using Spring boot, mongodb and React.js? 在React.js的父组件中使用react-router时,如何使用react context API将数据从父组件传递到子组件? - How do I use react context API to pass data from parent component to child component when using react-router in the parent component in React.js? 如何在没有捆绑器的情况下使用react.js? - How do I use react.js without a bundler? 如何在 react.js 中使用节点模块脚本? - how do I use a node module script in react.js? React.js:如何在渲染页面之前先运行 useEffect? - React.js: How to run useEffect first before rendering page? 如何使用node.js来运行react.js前端? - how do use node.js to run react.js front-end? meteor 如何使用upsert | 模拟调用效果时出现异常 TypeError: Cannot read properties of undefined (reading '_id') react.js - meteor How to use upsert | Exception while simulating the effect of invoking ” TypeError: Cannot read properties of undefined (reading ‘_id’) react.js 我怎样才能确保当我点击一个图标时,另一个页面会出现 React.js - How can I make sure that when I click on an icon another page appears with React.js 如何在 Chart.js 和 React.js 中使用 Axios API - How to use Axios API with Chart.js and React.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM