无法将变量作为 url 参数传递
can't pass variable as url parameter
我在使用以下代码时遇到了一些问题:
function SidebarChat() {
const [seed, setseed] = useState("")
useEffect(() => {
setseed(Math.floor(Math.random() * 5000));
}, []);
return (
<div className="sidebarChat">
<Avatar src={'https://avatars.dicebear.com/api/human/${seed}.svg'} />
</div>
)
}
我无法在 URL 中通过 ${seed}
。
当我通过时,它在 URL 行中显示错误,'${seed}' 被视为硬编码字符串。
我认为你需要删除字符串 const [seed, setseed] = useState("")
到 const [seed, setseed] = useState()
您在表达 src 时使用了引号而不是反引号,因此 ${seed} 不会按应有的方式被解释
解决问题:
<Avatar src={`https://avatars.dicebear.com/api/human/${seed}.svg`} />
要在字符串中添加变量,您必须将其放入模板文字中,如下所示:
`https://avatars.dicebear.com/api/human/${seed}.svg`
或
您还可以在单引号中使用变量,如下所示:
'https://avatars.dicebear.com/api/human/' + seed + '.svg'
了解更多 template literals
我在使用以下代码时遇到了一些问题:
function SidebarChat() {
const [seed, setseed] = useState("")
useEffect(() => {
setseed(Math.floor(Math.random() * 5000));
}, []);
return (
<div className="sidebarChat">
<Avatar src={'https://avatars.dicebear.com/api/human/${seed}.svg'} />
</div>
)
}
我无法在 URL 中通过 ${seed}
。
当我通过时,它在 URL 行中显示错误,'${seed}' 被视为硬编码字符串。
我认为你需要删除字符串 const [seed, setseed] = useState("")
到 const [seed, setseed] = useState()
您在表达 src 时使用了引号而不是反引号,因此 ${seed} 不会按应有的方式被解释
解决问题:
<Avatar src={`https://avatars.dicebear.com/api/human/${seed}.svg`} />
要在字符串中添加变量,您必须将其放入模板文字中,如下所示:
`https://avatars.dicebear.com/api/human/${seed}.svg`
或
您还可以在单引号中使用变量,如下所示:
'https://avatars.dicebear.com/api/human/' + seed + '.svg'
了解更多 template literals