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

React中使用map渲染数组时出现渲染异常问题求助

问题解决:React组件props传递失效

核心问题

你的SearchResultCard组件接收props的方式错误了。React组件的第一个参数是整个props对象,而不是你传递的单个result属性。现在你直接把result当作props对象使用,导致result.userName、result.avatarURL这些属性实际上是undefined(因为props对象里的属性是result,你需要从props里取出这个属性)。

这就解释了为什么只有Follow按钮显示:useState(result.isFollowed)里的result.isFollowed是undefined,React会把undefined当作false处理,所以渲染Follow按钮;而其他元素因为属性值是undefined,所以无法正常渲染。

修复步骤

1. 修正组件的props接收方式

把组件的参数改成解构props对象,取出result属性:

export default function SearchResultCard({ result }) {
    const [isFollowed,setIsFollowed] = useState(result.isFollowed);
    const handleFollowingClicked = ()=>{
        setIsFollowed(false);
    };
    const handleFollowClicked=()=>{
        setIsFollowed(true);
    };

    useEffect(()=>{console.log(result.userName)});

    return (
        <div className="search-result-card">
            <Link to={result.mainPageURL}>
                <div className="search-result-card-left">
                    <img src={result.avatarURL} alt={result.userName} className="search-result-img"/>
                    <p>{result.userName}</p>
                </div>
            </Link>
            {isFollowed ? (
                <button className="following-button" onClick={handleFollowingClicked}>Following</button> 
            ):(
                <button className="follow-button" onClick={handleFollowClicked}>Follow</button>
            )}
        </div>
    );
}

2. 给map遍历的元素添加key

React要求列表元素必须有唯一的key属性,这能帮助React优化渲染性能,避免警告。你可以用userName作为key(假设userName是唯一的):

export default function SearchBar(){
    return (
        <div className='searchBar'> 
            {sampleCards.map((result)=>{
                return (
                    <SearchResultCard key={result.userName} result={result}/>                  
                );
            })}
        </div>
    );
}

3. 可选:给useState初始值加默认值

为了防止result.isFollowed为undefined的情况,可以给useState加个默认值:

const [isFollowed,setIsFollowed] = useState(result.isFollowed ?? false);

验证效果

修复后,组件就能正确读取result里的所有属性,头像、用户名、对应状态的按钮都会正常渲染了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 04:55:32