繁体   English   中英

如何在 api 中将变量作为参数传递在 javascript 中调用 fetch,反应原生

[英]How to pass variable as a parameter in api call fetch in javascript, react native

我正在使用这个 api https://api.covid19api.com/live/country/south-africa来获取我的应用程序的结果。 我需要做的不是写国名,而是使用一个包含国名的变量。 我需要在 api url 中传递它

var countryName = "south-africa"
const fetchAPI = ()=> {
    return fetch("https://api.covid19api.com/live/country/$countryName")
    .then((response) => response.json())
    .then((result) => {
      //console.log(result)

您可以使用模板字符串来实现使用反引号`而不是引号"。

var countryName = "south-africa"
const fetchAPI = ()=> {
    return fetch(`https://api.covid19api.com/live/country/${countryName}`)
    .then((response) => response.json())
    .then((result) => {
      //console.log(result)

如何在 javascript 中使用模板字符串。

 var foo = 'Hello world' // expected result "my variable foo = Hello world" console.log(`my variable foo = ${foo}`)

我希望这有帮助。

解决方案

我的赌注是使用带有魔术引号的 Javascript 字符串格式:

这会导致

var countryName = "south-africa"
const fetchAPI = ()=> {
    return fetch(`https://api.covid19api.com/live/country/${countryName}`)
    .then((response) => response.json())
    .then((result) => {
      //console.log(result)

参考

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

您可以考虑使用字符串文字。

var countryName = "south-africa"
const fetchAPI = ()=> {
    return fetch(`https://api.covid19api.com/live/country/${countryName}`)
    .then((response) => response.json())
    .then((result) => {

    }

或字符串连接:

var countryName = "south-africa"
const fetchAPI = ()=> {
    return fetch("https://api.covid19api.com/live/country/" + countryName)
    .then((response) => response.json())
    .then((result) => {

    }

资源: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

暂无
暂无

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

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