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

React中无法向表格追加数据,报no-unused-expressions错误求助

Why You're Seeing the Error

The error Expected an assignment or function call and instead saw an expression stems from your map callback in the table section. When you use curly braces {} with an arrow function, you’re defining a block body—this means you need to explicitly return the JSX element you want to render. Right now, you’re creating the <tr> element but not returning it, so the expression goes unused.

Additionally, your items in the obj state don’t have an id property, so using item.id as the key prop is invalid (it will be undefined, which React will warn about).


Fixed Code

Here’s your code with the errors resolved plus some UX improvements:

import React, { Fragment, useState } from "react";

const Table = () => {
  const [formData, setFormData] = useState({ name: "", email: "" });
  const [items, setItems] = useState([]);

  const handleSubmit = (event) => {
    event.preventDefault();
    // Add a unique ID to each new item (using Date.now() for simplicity)
    setItems([...items, { ...formData, id: Date.now() }]);
    // Clear the form after submission
    setFormData({ name: "", email: "" });
  };

  const handleInputChange = (event) => {
    event.persist();
    setFormData((prev) => ({ ...prev, [event.target.name]: event.target.value }));
  };

  return (
    <Fragment>
      <div className="container-fluid">
        <form className="form-inline" onSubmit={handleSubmit}>
          <input
            className="form-control"
            type="text"
            name="name"
            placeholder="Add Name"
            onChange={handleInputChange}
            value={formData.name}
            required
          />
          <input
            className="form-control"
            type="email"
            name="email"
            placeholder="Add Email"
            onChange={handleInputChange}
            value={formData.email}
            required
          />
          <input type="submit" value="Add" className="btn btn-dark" />
        </form>
        <table className="table-striped">
          <tbody>
            <tr>
              <th>Name</th>
              <th>Email</th>
            </tr>
            {/* Use implicit return in map, and valid unique key */}
            {items.map((item) => (
              <tr key={item.id}>
                <td>{item.name}</td>
                <td>{item.email}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </Fragment>
  );
};

export default Table;

Key Changes Explained
  1. Fixed the map Callback: Switched to parentheses () instead of curly braces {} for the arrow function, which enables implicit return of the JSX element. Alternatively, you could keep the curly braces and add a return statement inside.
  2. Added Unique id for Keys: When adding a new item to the items state, we generate a unique id using Date.now()—this ensures React can efficiently track list items and avoid warnings.
  3. Cleared Form on Submit: After submitting the form, we reset the formData state to empty strings, which clears the input fields for a smoother user experience.
  4. Renamed State Variables: Changed count to formData and obj to items to make the code more readable and descriptive.
  5. Removed Redundant Check: The obj.length !== 0 check isn’t necessary—if the array is empty, map will just return nothing, so we can omit it to simplify the code.

Additional Optimizations

If you want to enhance this further, consider:

  • Using a more robust method for generating unique IDs (like the uuid library) instead of Date.now() (though Date.now() works fine for simple use cases).
  • Adding custom email format validation (beyond the HTML5 type="email" check) if stricter rules are needed.
  • Adding a delete button for each table row to enable full CRUD functionality.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:00:17