我有以下從 Apollo Server 后端獲取資料的代碼。資料采用以下格式:
{ name: 'geodude', url: 'https://pokeapi.co/api/v2/pokemon/74/' },
{ name: 'graveler', url: 'https://pokeapi.co/api/v2/pokemon/75/' },
為了顯示影像,我拆分了這個 url 字串,最后得到了 74 或 75 的 id。但是我如何在 JSX 中拆分它,因為它不允許我宣告任何變數。
return (
<div className="App">
{data.pokemonList.map((data) => (
let a = data.url.split(/) // this gets the id from my url
const b = "https://raw/${a}.png"; //use it in the string like this
但顯然我不能在 JSX 中做到這一點。此外,我不能在回傳之外執行此操作,因為我必須像這樣對所有映射值進行拆分。有沒有更簡單的方法來做到這一點?
uj5u.com熱心網友回復:
當然,你可以在 JSX 中做到這一點——你可以把它全部放在一個運算式中,例如:
{data.pokemonList.map((data) =>
<img src={
`https://raw/${data.url.match(/\d (?=\/$)/)[0]}.png`
}>
)}
或者創建一個塊,允許你宣告變數,然后在最后回傳 JSX:
{data.pokemonList.map((data) => {
const num = data.url.match(/\d (?=\/$)/)[0];
const url = `https://raw/${num}.png`
return <img src={src}>;
})}
請注意,您需要反引號才能插入帶有${}(不是“)的字串,并且您的 currenta將為您提供一個陣列,而不是字串,因此插值${a}不起作用。您需要從網址。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/458927.html
