[英]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.