繁体   English   中英

我在使用 javascript 数组时遇到了一个困难且关键的问题?

[英]I am facing a difficult and critical problem with javascript array?

我正在构建一个 React-Nextjs 应用程序。 我在我的项目中连接 graphql api。 我写了一个请求函数——

await axios.post(process.env.NEXT_PUBLIC_API_URL as string, {
    query: `
    query isListed {
        isListed(name: ["Thor: Love and Thunder"]) {
          name
          isWatchlisted
          isWishlisted
        }
      }`
})
    .then(res => console.log(res))
    .catch(err => console.log(err))

这工作正常。 在这里你可以看到["Thor: Love and Thunder"] ,我正在发送静态数据。 当我尝试使用动态数据时,我遇到了问题。 api文档说他们只接受字符串数组。

这是我尝试使用动态数据时的示例-

const test = ["Thor: Love and Thunder"]
//Here I try to use this test data

await axios.post(process.env.NEXT_PUBLIC_API_URL as string, {
    query: `
    query isListed {
        isListed(name: ${test}) {
          name
          isWatchlisted
          isWishlisted
        }
      }`
})
    .then(res => console.log(res))
    .catch(err => console.log(err))

当我尝试它时,它给了我一个语法错误。 但我不明白这两个例子有什么不同。 请帮我。

您正在插入字符串。 数组,当强制转换为字符串时,将用逗号连接,但不带括号。 例如, let a=[1,2,3]; let s=`${a}`; let a=[1,2,3]; let s=`${a}`; 将为您提供值为'1,2,3'的字符串 s。

在您的情况下,您有两个选择:使用字符串文字而不是数组,或者在插值时使用JSON.stringify

所以要么

const test = '["Thor: Love and Thunder"]'
…

或者

…
query: `
    query isListed {
        isListed(name: ${JSON.stringify(test)}) {
          name
          isWatchlisted
          isWishlisted
        }
      }`
…

暂无
暂无

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

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