在表单中使用 useState 更新数组

Updating an array with useState in a form

在下文中,我已验证 setNewItem 有效,但项目未更新,因此函数 handleSubmit 一定存在问题。这里出了什么问题?

import "./styles.css";
import React, {useState, useEffect} from 'react';


export default function App() {
  const [items, setItems] = useState(['first item']);
  const [newItem, setNewItem] = useState("");
  
  const handleSubmit = (event, newItem, items) => {
    event.preventDefault();
    setItems([ newItem, ...items]);
  };

  const handleChange = (event) => {
    setNewItem(event.target.value);
  }
  
  return (
    <div>
      <form>
        <input type="text" 
               value={newItem} 
               onChange={handleChange}
              />
        <input type="submit" 
               value="submit"
               onSubmit={handleSubmit}
               />
      </form> 
    <ul>
      {items.map( (i) => {
        return(<li>{i}</li>)
      })}
    </ul> 
    </div>
  );
}

https://codesandbox.io/s/new?file=/src/App.js:0-797

试试这个

import "./styles.css";
import React, { useState, useEffect } from "react";

export default function App() {
  const [items, setItems] = useState(["first item"]);
  const [newItem, setNewItem] = useState("");

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log("here");
    setItems([newItem, ...items]);
  };

  const handleChange = (event) => {
    setNewItem(event.target.value);
  };

  return (
    <div>
      <form>
        <input type="text" value={newItem} onChange={handleChange} />
        <input type="button" value="submit" onClick={handleSubmit} />
      </form>
      <ul>
        {items.map((i) => {
          return <li>{i}</li>;
        })}
      </ul>
    </div>
  );
}

你需要改变并尝试这个。

  const handleSubmit = (event) => {
    event.preventDefault();
    setItems([ newItem, ...items]);
  };

 ...
 ...
 ...

 <input type="submit" 
      value="submit"
      onSubmit={event => handleSubmit(event)}
 />