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

React无渲染表格编辑:增删行同步数据库技术咨询

Hey there! Let's break down how to implement these two features step by step—since you already have data fetching and table display working, you're already halfway there!

1. Add a Delete Button to Each Table Row

Here's how to make the "X" button remove the row from both the table and your database:

  • Render the Delete Button: In your table row mapping logic, add a button for each entry. Pass the row's unique ID to the click handler so you know which item to target:

    {data.map(row => (
      <tr key={row.id}>
        <td>{row.name}</td>
        <td>{row.description}</td>
        {/* Add the delete button */}
        <td>
          <button 
            onClick={() => handleDelete(row.id)}
            style={{ backgroundColor: '#dc3545', color: 'white', border: 'none', borderRadius: '4px', padding: '4px 8px', cursor: 'pointer' }}
          >
            X
          </button>
        </td>
      </tr>
    ))}
    
  • Implement the Delete Handler: Create an async function that first calls your backend's DELETE endpoint, then updates your local state to remove the deleted item. Always handle errors to avoid inconsistent data:

    const [data, setData] = useState([]); // Your existing table data state
    
    const handleDelete = async (itemId) => {
      try {
        // Call backend API to delete from DB
        const response = await fetch(`/api/items/${itemId}`, {
          method: 'DELETE',
          headers: {
            'Content-Type': 'application/json',
            // Add auth headers here if your API requires them
          },
        });
    
        if (!response.ok) throw new Error('Delete request failed');
    
        // Update local state to remove the deleted item
        setData(prev => prev.filter(item => item.id !== itemId));
      } catch (err) {
        console.error('Delete error:', err);
        alert('Failed to delete the item. Please try again.');
      }
    };
    

Pro Tip: Always wait for the backend to confirm deletion before updating your local state—this prevents cases where the API fails but the row disappears from the table, leading to data mismatch.

2. Add a New Row to the Table and Database

To let users add new entries that sync to both the table and your DB, follow these steps:

  • Set Up State for the New Entry: Create a state variable to hold input values for the new row:

    const [newItem, setNewItem] = useState({
      // Match your database fields, e.g., name, description, etc.
      name: '',
      description: ''
    });
    
  • Render an Add Form: Add a simple form above or below your table to capture new data:

    <form onSubmit={handleAdd} style={{ marginBottom: '16px', gap: '8px', display: 'flex' }}>
      <input
        type="text"
        placeholder="Item name"
        value={newItem.name}
        onChange={(e) => setNewItem(prev => ({ ...prev, name: e.target.value }))}
        required
      />
      <input
        type="text"
        placeholder="Item description"
        value={newItem.description}
        onChange={(e) => setNewItem(prev => ({ ...prev, description: e.target.value }))}
        required
      />
      <button type="submit" style={{ backgroundColor: '#28a745', color: 'white', border: 'none', borderRadius: '4px', padding: '4px 12px' }}>
        Add Row
      </button>
    </form>
    
  • Implement the Add Handler: Write an async function that sends the new data to your backend's POST endpoint, then adds the returned (database-generated) item to your local state:

    const handleAdd = async (e) => {
      e.preventDefault();
    
      try {
        // Send new item data to backend to save in DB
        const response = await fetch('/api/items', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            // Add auth headers if needed
          },
          body: JSON.stringify(newItem),
        });
    
        if (!response.ok) throw new Error('Add request failed');
    
        // Get the full item (including DB-generated ID) from the response
        const addedItem = await response.json();
    
        // Update local state to include the new item
        setData(prev => [...prev, addedItem]);
    
        // Reset the form
        setNewItem({ name: '', description: '' });
      } catch (err) {
        console.error('Add error:', err);
        alert('Failed to add the item. Please try again.');
      }
    };
    

Important Note: Make sure your backend returns the full created item (with its unique ID) after the POST request—this ensures your local state matches the database, which is crucial for future operations like deleting the new row.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:18:24