[英]How to access data outside of a Promise
我正在制作一個反應應用程序,該應用程序向 OpenWeather 發送 API 調用以獲取城市的天氣數據(由用戶指定)。 以下是該調用的請求:
async function getAPI() {
const apiCall = await axios.get(apiLink).then(res => {
res = {
temp : res.data.main.temp - 273.15,
weatherIcon : res.data.weather[0].icon,
windSpeed : res.data.wind.speed
}
return res
});
return apiCall
}
const weatherData = getAPI()
請注意,我嘗試將來自 API 響應的數據存儲在名為 weatherData 的變量中。 這樣我就可以在需要時簡單地調用該變量,這是使用此變量的 HTML 代碼示例:
<p>
temperature is {weatherData.temp} Celcius
</p>
這導致 weatherData.temp 出於某種原因根本沒有顯示在瀏覽器端。 console.log(weatherData) 在控制台中打印:
Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
temp: 29.53
weatherIcon: "04d"
windSpeed: 1.59
[[Prototype]]: Object
如何從 promise 中提取數據,以便我可以輕松引用所述數據以在 HTML 代碼中使用?
下面的答案是如果您使用功能組件和反應鈎子。
可以 go 兩個方向:
const fetchWeather = async () => {
try {
const res = await axios.get(apiLink);
console.log(res);
setWeather(res.data); //Im not sure what the exact response is, but you can access the keys you need.
// you can then set the data you need to your state to render it.
} catch (error) {
// handle error
}
}
或者你可以使用.then.catch
const fetchWeather = async () => {
axios.get(apiLink)
.then((res) => {
setWeather(res.data); //Im not sure what the exact response is, but you can access the keys you need.
// set the data you need from the respones to your state.
})
.catch((err) => {
// handle error
})
}
在這兩種情況下,您都可以在 useEffect 掛鈎中調用 function。
useEffect(() => {
fetchWeather()
}, [])
一般來說,我的偏好是將您從 Api 獲得的響應設置為本地 state(意思是您的頁面/組件的 state)。 然后將 state 渲染到您的 jsx。
因此,如果您使用反應掛鈎,您的 state 可能如下所示:
const [weather, setWeather] = useState({});
最后編輯:最后,您可以在 jsx/html 中參考您的 state。 假設您的天氣 state 如下所示:
{
temp: '50 degrees'
}
在您的 JSX 中,您可以這樣引用它:
<>
<div>{weather.temp}</div>
</>
您需要等待 getAPI function。 我假設您不只是在組件中調用 function 並通過 useEffect in react 調用它。 IMO 我會在 useEffect 中調用 getAPI function 並將響應設置為 state。 通過將天氣數據設置為 state,您將能夠調用它並在 jsx 中呈現它。 您將此問題標記為反應,所以我假設您正在使用反應。
useEffect 中的示例
export default function App() {
const [weatherData, setWeatherData] = useState(null);
const apiLink = "your api url";
useEffect(() => {
const getAPI = async () => {
const apiCall = await axios
.get(apiLink)
.then((res) => {
res = {
temp: res.data.main.temp - 273.15,
weatherIcon: res.data.weather[0].icon,
windSpeed: res.data.wind.speed
};
return res;
})
.catch((error) => {
console.error(error.message);
});
setWeatherData(apiCall);
};
getAPI();
}, []);
if (!weatherData) {
return null;
}
return (
<div className="App">
<p>temperature is {weatherData.temp} Celcius</p>
</div>
);
}
這是一個代碼框,向您展示一個工作示例,您必須更新沙盒中的 apiLink 以使其正常工作,但這就是您能夠實現您正在尋找的結果的方式: https://codesandbox.io /s/compassionate-mclaren-n4rgxs?file=/src/App.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.