从函数内更新全局变量

Updating a global variable from within a function

我正在定义两个变量:

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 调用并将它们存储到状态的正确方法,但这对我来说是有意义的。非常感谢任何反馈。

您应该在 React 中使用 useState 来存储您的变量。 how to use

正在创建

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} />