You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用.map生成部署页面链接的语法问题求助

解决React中GitHub Pages部署URL拼接的语法错误

问题分析

你遇到的核心问题是JSX属性的语法使用错误:在JSX中,当需要给属性赋值JavaScript表达式时,必须将整个表达式包裹在{}中,不能混合使用字符串引号和零散的{}。你之前写的href='https://chrispyrice024.github.io/'+ {list.name} +'/'不符合JSX语法规范,所以会抛出意外令牌的错误。

正确的URL拼接写法

有两种可行的方式来正确拼接部署URL:

  1. 模板字符串写法(推荐,可读性更高)
href={`https://chrispyrice024.github.io/${list.name}/`}
  1. 字符串拼接写法
href={'https://chrispyrice024.github.io/' + list.name + '/'}

修正后的完整代码

import React from 'react';
import { useState, useEffect } from 'react';

export default function Repos () {
    const [list, setList] = useState([]);

    useEffect(() => {
        fetch('https://api.github.com/users/ChrispyRice024/starred?per_page=10')
            .then(response => response.json())
            .then(data => setList(data));
    }, []);

    return (
        <div>
            <h1>Top Repositories</h1>
            <ul>
                {list.map(repo => (
                    <li key={repo.id}>
                        <a href={`https://chrispyrice024.github.io/${repo.name}/`}>
                            {repo.name}
                        </a>
                    </li>
                ))}
            </ul>
        </div>
    );
}

额外优化说明:

  • 将map的参数名从list改为repo,避免和状态变量重名,提升代码可读性
  • 给列表项li添加key属性(使用仓库的id),符合React列表渲染规范,避免控制台警告

内容的提问来源于stack exchange,提问作者user20276841

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 03:20:14