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

React预算追踪应用:提交表单后自动清空的实现问题

Solution

To automatically clear the form after submitting an expense, call your reset() function right after dispatching the ADD_EXPENSE action in the onSubmit handler. This ensures the expense is added first, then the form fields are reset to empty values.

Additionally, fix the for attribute on your labels to htmlFor (since for is a reserved keyword in JavaScript, React uses htmlFor instead to avoid conflicts and accessibility issues).

Here's the corrected code:

import React, { useContext, useState } from 'react';
import { AppContext } from '../context/AppContext';
import { v4 as uuidv4 } from 'uuid';

const AddExpenseForm = () => {
    const { dispatch } = useContext(AppContext);

    const [name, setName] = useState('');
    const [cost, setCost] = useState('');

    const onSubmit = (event) => {
        event.preventDefault();

        const expense = {
            id: uuidv4(),
            name: name,
            cost: parseInt(cost),
        };

        dispatch({
            type: 'ADD_EXPENSE',
            payload: expense,
        });

        // Reset form fields after submitting
        reset();
    };

    const reset = () => {
        setName('');
        setCost('');
    }
    
    return (
        <form onSubmit={onSubmit}>
            <div className='row'>
                <div className='col-sm'>
                    <label htmlFor='name'>Name</label>
                    <input
                        required='required'
                        type='text'
                        className='form-control'
                        id='name'
                        value={name}
                        onChange={(event) => setName(event.target.value)}
                    ></input>
                </div>
                <div className='col-sm'>
                    <label htmlFor='cost'>Cost</label>
                    <input
                        required='required'
                        type='text'
                        className='form-control'
                        id='cost'
                        value={cost}
                        onChange={(event) => setCost(event.target.value)}
                    ></input>
                </div>
                <div className='col-sm'>
                    <button type='submit' className='btn btn-primary mt-3'>
                        Save
                    </button>
                    <button type='reset' className='btn btn-warning mt-3' onClick={reset}>Reset</button>
                </div>
            </div>
        </form>
    );
};

export default AddExpenseForm;

Key Notes:

  • The dispatch action updates your context with the new expense, refreshing the budget totals and expense list.
  • Calling reset() immediately after dispatch clears the controlled input fields by resetting their associated state variables.
  • The htmlFor fix resolves potential React warnings and maintains proper label-input association for accessibility.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 13:00:23