所以在按下<button type="submit" className="btn btn-primary">Create</button>后,我创建了一张带有英雄的卡片.然后, .then(() => clearFields())帮助我清除输入字段,因为с再次点击СReate按钮将返回一张空白卡片.也就是说,我看到卡上的信息被正确清除了.但从视觉上看,这些字段仍处于填充状态.

按下<button type="submit" className="btn btn-primary">Create</button>键后,如何使输入字段清晰?

import { useState, useEffect } from "react";
import { v4 as uuidv4 } from 'uuid';
import { useDispatch } from 'react-redux';
import { heroCreate } from '../../actions';
import { useHttp } from '../../hooks/http.hook';

const HeroesAddForm = () => {
    const [name, setName] = useState('');
    const [description, setDescription] = useState('');
    const [element, setElement] = useState('');
    const {request} = useHttp();

    const dispatch = useDispatch();

    const clearFields = () => {
        setName('');
        setDescription('');
        setElement('');
    }
    const handleSubmit = (event) => {
        event.preventDefault();

        const newHero = {
            id: uuidv4(),
            name: name,
            description: description,
            element: element
        }
        request("http://localhost:3001/heroes", "POST", JSON.stringify(newHero))
        .then(dispatch(heroCreate(newHero)))
        .then(() => clearFields())
        .catch(err => console.log(err));   
        
    }
    return (
        <form className="border p-4 shadow-lg rounded" onSubmit={handleSubmit}>
            <div className="mb-3">
                <label htmlFor="name" className="form-label fs-4">Name of new hero</label>
                <input
                    required
                    type="text"
                    name="name"
                    className="form-control"
                    // id="name" 
                    onChange={event => setName(event.target.value)}
                    placeholder="What is your name?" />
            </div>

            <div className="mb-3">
                <label htmlFor="text" className="form-label fs-4">Description</label>
                <textarea
                    required
                    name="text"
                    className="form-control"
                    // id="text" 
                    placeholder="Tell us something about your hero"
                    onChange={event => setDescription(event.target.value)}
                    style={{ "height": '130px' }} />
            </div>

            <div className="mb-3">
                <label htmlFor="element" className="form-label">Choose hero element</label>
                <select
                    required
                    className="form-select"
                    id="element"
                    onChange={event => setElement(event.target.value)}
                    name="element">
                    <option >I have the element of...</option>
                    <option value="fire">Fire</option>
                    <option value="water">Water</option>
                    <option value="wind">Wind</option>
                    <option value="earth">Earth</option>
                </select>
            </div>

            <button type="submit" className="btn btn-primary">Create</button>
        </form>
    )
}

export default HeroesAddForm;

我用这种方式编写代码是因为我认为.then(() => clearFields())会在执行查询和调度操作创建者之后清除字段.

推荐答案

Issue

当然,clearFields处理程序会重置本地的namedescriptionelement状态值,但由于表单字段不是104,因此它们实际上不会更新,直到您手动编辑输入.

PUT请求响应处理中还有一个小问题,即立即调用dispatch,而不是在request解析后调用.

Solution

你有两个简单的 Select :

完全受控输入

完全受控的输入使用REACT状态,并将value102两个处理程序都传递给输入.换句话说,这个值是由国家控制的.

const HeroesAddForm = () => {
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [element, setElement] = useState("");
  const { request } = useHttp();

  const dispatch = useDispatch();

  const clearFields = () => {
    setName("");
    setDescription("");
    setElement("");
  };

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

    const newHero = {
      id: uuidv4(),
      name,
      description,
      element
    };

    request("http://localhost:3001/heroes", "POST", JSON.stringify(newHero))
      .then(() => dispatch(heroCreate(newHero))) // <-- arrow function call dispatch
      .then(clearFields)
      .catch(console.log);
  };

  return (
    <form className="border p-4 shadow-lg rounded" onSubmit={handleSubmit}>
      <div className="mb-3">
        <label htmlFor="name" className="form-label fs-4">
          Name of new hero
        </label>
        <input
          required
          type="text"
          name="name"
          className="form-control"
          onChange={(event) => setName(event.target.value)}
          value={name} // <-- provide value
          placeholder="What is your name?"
        />
      </div>

      <div className="mb-3">
        <label htmlFor="text" className="form-label fs-4">
          Description
        </label>
        <textarea
          required
          name="description"
          className="form-control"
          placeholder="Tell us something about your hero"
          onChange={(event) => setDescription(event.target.value)}
          value={description} // <-- provide value
          style={{ height: "130px" }}
        />
      </div>

      <div className="mb-3">
        <label htmlFor="element" className="form-label">
          Choose hero element
        </label>
        <select
          required
          className="form-select"
          id="element"
          onChange={(event) => setElement(event.target.value)}
          value={element} // <-- provide value
          name="element"
        >
          <option disabled value="">
            I have the element of...
          </option>
          <option value="fire">Fire</option>
          <option value="water">Water</option>
          <option value="wind">Wind</option>
          <option value="earth">Earth</option>
        </select>
      </div>

      <button type="submit" className="btn btn-primary">
        Create
      </button>
    </form>
  );
};

完全不受控制的输入

完全不受控制的输入不使用REACT状态,并且不向输入传递valueonChange个处理程序.使用form元素的onSubmit处理程序访问表单字段值并重置表单.

const HeroesAddForm = () => {
  const { request } = useHttp();

  const dispatch = useDispatch();

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

    const { description, element, name } = event.target;

    const newHero = {
      id: uuidv4(),
      name: name.value,
      description: description.value,
      element: element.value
    };

    request("http://localhost:3001/heroes", "POST", JSON.stringify(newHero))
      .then(() => dispatch(heroCreate(newHero)))
      .then(() => event.target.reset())
      .catch(console.log);
  };

  return (
    <form className="border p-4 shadow-lg rounded" onSubmit={handleSubmit}>
      <div className="mb-3">
        <label htmlFor="name" className="form-label fs-4">
          Name of new hero
        </label>
        <input
          required
          type="text"
          name="name"
          className="form-control"
          placeholder="What is your name?"
        />
      </div>

      <div className="mb-3">
        <label htmlFor="text" className="form-label fs-4">
          Description
        </label>
        <textarea
          required
          name="description"
          className="form-control"
          placeholder="Tell us something about your hero"
          style={{ height: "130px" }}
        />
      </div>

      <div className="mb-3">
        <label htmlFor="element" className="form-label">
          Choose hero element
        </label>
        <select
          required
          className="form-select"
          id="element"
          defaultValue="" // <-- default value
          name="element"
        >
          <option disabled value="">
            I have the element of...
          </option>
          <option value="fire">Fire</option>
          <option value="water">Water</option>
          <option value="wind">Wind</option>
          <option value="earth">Earth</option>
        </select>
      </div>

      <button type="submit" className="btn btn-primary">
        Create
      </button>
    </form>
  );
};

Javascript相关问答推荐

在贝塞尔曲线的直线上找不到交叉点:(使用@Pomax的bezier.js)

微软Edge Select 间隙鼠标退出问题

TypScript界面中的Infer React子props

从PWA中的内部存储读取文件

从mat—country—select获取整个Country数组

无法在nextjs应用程序中通过id从mongoDB删除'

角色 map 集/spritebook动画,用户输入不停止在键上相位器3

为什么这个JS模块在TypeScript中使用默认属性导入?""

在服务器上放置了Create Reaction App Build之后的空白页面

Puppeteer上每页的useProxy返回的不是函数/构造函数

MarkLogic-earch.suggest不返回任何值

TypeError:无法读取未定义的属性(正在读取';宽度';)

以编程方式聚焦的链接将被聚焦,但样式不适用

AddEventListner,按键事件不工作

当从其他文件创建类实例时,为什么工作线程不工作?

使用jQuery find()获取元素的属性

Phaser3 preFX addGlow不支持zoom

在渲染turbo流之后滚动到元素

Django导入问题,无法导入我的应用程序,但我已在设置中安装了它

如何从Reaction-Redux中来自API调用的数据中筛选值