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

React类组件中使用箭头函数(=>)出现语法错误及employee未定义问题求助

Fixing Your React Class Component Issues

Hey there! I see two key issues in your ListEmployeeComponent that are causing those errors—let's break them down and fix them right away.

The Core Problems

  1. Missing curly braces for JS expressions in JSX: In your <tbody> section, you're directly writing this.state.employees.map(...) without wrapping it in {}. JSX treats anything not inside {} as plain text, so your arrow function isn't being executed as JavaScript at all. That's why the syntax isn't recognized, and the employee variable is "undefined" (the code never runs to create that variable).
  2. No fallback for empty employee list: While not causing your current error, it's a good practice to handle cases where employees is empty so your UI doesn't show an empty table body.

Fixed Component Code

class ListEmployeeComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      employees: [],
    };
  }

  render() {
    return (
      <div>
        <h2 className="text-center">Employees List</h2>
        <div className="row">
          <table className="table table-striped table-bordered">
            <thead>
              <tr>
                <th>Employee First Name</th>
                <th>Employee Last Name</th>
                <th>Employee Email ID</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {/* Wrap the map function in curly braces to execute it as JS */}
              {this.state.employees.length > 0 ? (
                this.state.employees.map((employee) => (
                  <tr key={employee.id}>
                    <td>{employee.firstname}</td>
                    <td>{employee.lastname}</td>
                    <td>{employee.emailId}</td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan="4" className="text-center">No employees found</td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    );
  }
}

export default ListEmployeeComponent;

Key Fixes Explained

  • Wrapping map in {}: This tells React to evaluate the code inside as a JavaScript expression, so the arrow function runs correctly, and the employee variable is properly defined for each item in the array.
  • Empty state handling: The ternary check (employees.length > 0 ? ... : ...) shows a friendly message when there are no employees, which improves the user experience and avoids an empty table body.
  • Typo correction: Fixed taable-bordered to table-bordered so your table styling works as intended.

内容的提问来源于stack exchange,提问作者Minhaj Ul Islam - Moon1570

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 19:32:49