简体   繁体   English

从 function 中更新全局变量

[英]Updating a global variable from within a function

I am defining two variables:我正在定义两个变量:

var information;
var secondary_information;

I update these variables within my function:我在我的 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
};
}

When I console log the variables from within the function it works as intended.当我从 function 控制台记录变量时,它按预期工作。

I am trying to pass the variables down as props to a react component but it keeps passing an empty object instead:我试图将变量作为道具传递给反应组件,但它一直传递一个空的 object :

return (
<div className="App">
  <Filters />
  <Button variant="primary" onClick={fetchInfo}>
    Randomizer
  </Button>{" "}
  <Result info={information} />
</div>
);

Additionally, I have no clue if this is the correct way I should be going about making these API calls and storing them into state but this is the way that made sense to me.此外,我不知道这是否是我应该进行这些 API 调用并将它们存储到 state 中的正确方法,但这对我来说是有意义的方式。 Any feedback is greatly appreciated.非常感谢任何反馈。

You should be using useState in react to store your variables.您应该在反应中使用 useState 来存储您的变量。 how to use如何使用

Creating创造

const [information, setInformation] = useState(null);

Updateing更新

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

Then passing the state to props should stay the same.然后将 state 传递给 props 应该保持不变。

<Result info={information} />

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM