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

使用三元运算符结合数组映射条件渲染时遇语法错误求助

React用户列表组件语法错误修复及逻辑优化

我尝试从json placeholder获取用户数组数据,通过三元运算符判断数组是否存在元素,存在则映射渲染每个用户信息,不存在则返回提示文本,但代码出现语法错误。

原代码

import React, { useEffect, useState } from "react";
import { fetchUsers } from "../../lib/functions";

const Users = () => {
    const [users, setUsers] = useState([]);

    useEffect(() => {
        fetchUsers().then(res => setUsers(res.data))
    }, []);
    return (
        <div className="users">
            <h1>Users</h1>
            {users.length ? users.map((user) => {
                (<div key="id">
                    <h4>{users.name}</h4>
                    <h5>{users.email}</h5>
                    <h6>{users.username}</h6>
                    <p>{users.address}</p>
                </div>) :
                (
                    <div>
                        <p>User not found.</p>
                    </div>
                )})}
        </div>
    );
}

export default Users;

报错信息

ERROR in [eslint]
src/components/users/Users.js
Line 19:23:  Parsing error: Missing semicolon. (19:23)

webpack compiled with 2 errors

错误分析与修复方案

  • 语法结构混乱:三元运算符的分支位置错误,map回调使用大括号却未返回JSX,导致ESLint解析报错。需将三元的else分支移到map外部,map回调改用小括号省略return,或显式声明return。
  • 变量引用错误:遍历map时错误引用数组users,应使用当前遍历项user。
  • Key属性无效:key需设置唯一标识值user.id,而非固定字符串"id"。
  • 对象渲染异常:address是嵌套对象,直接渲染会显示[object Object],需提取具体属性拼接成可读文本。

修复后代码

import React, { useEffect, useState } from "react";
import { fetchUsers } from "../../lib/functions";

const Users = () => {
    const [users, setUsers] = useState([]);

    useEffect(() => {
        fetchUsers().then(res => setUsers(res.data))
    }, []);

    return (
        <div className="users">
            <h1>Users</h1>
            {users.length > 0 ? (
                users.map((user) => (
                    <div key={user.id}>
                        <h4>{user.name}</h4>
                        <h5>{user.email}</h5>
                        <h6>{user.username}</h6>
                        <p>
                            {user.address.street}, {user.address.city}
                        </p>
                    </div>
                ))
            ) : (
                <div>
                    <p>未找到用户。</p>
                </div>
            )}
        </div>
    );
}

export default Users;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 06:45:37