[英]Updating a global variable from within a function
我正在定義兩個變量:
var information;
var secondary_information;
我在我的 function 中更新了這些變量:
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
};
}
當我從 function 控制台記錄變量時,它按預期工作。
我試圖將變量作為道具傳遞給反應組件,但它一直傳遞一個空的 object :
return (
<div className="App">
<Filters />
<Button variant="primary" onClick={fetchInfo}>
Randomizer
</Button>{" "}
<Result info={information} />
</div>
);
此外,我不知道這是否是我應該進行這些 API 調用並將它們存儲到 state 中的正確方法,但這對我來說是有意義的方式。 非常感謝任何反饋。
您應該在反應中使用 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
})
然后將 state 傳遞給 props 應該保持不變。
<Result info={information} />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.