我正在定義兩個變數:
var information;
var secondary_information;
我在我的函式中更新這些變數:
async function fetchInfo() {
var num = Math.floor(Math.random() * 20 1);
const url = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${pos.current.coords.latitude},${pos.current.coords.longitude}&radius=12000&type=restaurant&key=${key}`;
await fetch(url)
.then((response) => response.json())
.then((data) => setSearchResponse(data))
.then(console.log("api request fired."));
let place_id = searchResponse.results[num].place_id;
const secondary_url = `https://maps.googleapis.com/maps/api/place/details/json?fields=formatted_phone_number,opening_hours,formatted_address&place_id=${place_id}&key=${key}`;
await fetch(secondary_url)
.then((response) => response.json())
.then((data) => setsecondarySearchResponse(data))
.then(console.log("secondary api request fired."));
information = {
name: searchResponse.results[num].name,
open_now: searchResponse.results[num].opening_hours.open_now,
rating: searchResponse.results[num].rating,
price: searchResponse.results[num].price_level
};
secondary_information = {
phone_number: secondarySearchResponse.result.formatted_phone_number,
daily_hours: secondarySearchResponse.result.opening_hours.weekday_text,
address: secondarySearchResponse.result.formatted_address
};
}
當我從函式中控制臺記錄變數時,它會按預期作業。
我試圖將變數作為道具傳遞給反應組件,但它一直傳遞一個空物件:
return (
<div className="App">
<Filters />
<Button variant="primary" onClick={fetchInfo}>
Randomizer
</Button>{" "}
<Result info={information} />
</div>
);
此外,我不知道這是否是我應該進行這些 API 呼叫并將它們存盤到狀態中的正確方式,但這對我來說是有意義的方式。非常感謝任何反饋。
uj5u.com熱心網友回復:
您應該在反應中使用 useState 來存盤您的變數。 如何使用
創造
const [information, setInformation] = useState(null);
更新
setInformation({
name: searchResponse.results[num].name,
open_now: searchResponse.results[num].opening_hours.open_now,
rating: searchResponse.results[num].rating,
price: searchResponse.results[num].price_level
})
然后將狀態傳遞給道具應該保持不變。
<Result info={information} />
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/415996.html
標籤:
