使用 useState 和 React 的 TodoList - 更新 todoList 的问题

我在使用 React 和 useState 更新我的 todoList 时遇到问题...我应该尝试使用“推送”还是其他方式来更新我的列表?


非常感谢您 !!


import React, { useState } from "react";


const App = () => {

  // State search et sa fonction de modification

  const [search, setSearch] = useState("");

  const updateSearch = (e) => {

    setSearch(e.target.value);

    console.log(search);

  };

  // State de liste et sa fonction de modification

  const [list, setList] = useState([]);

  const updateList = () => {

    setList([...list, search]);

  };


  return (

    <div>

      <h1>Welcome on your todolist</h1>

      <br />

      <input type="text" onChange={updateSearch} value={search} />

      <button onClick={updateList}>enter</button>

      <ul></ul>

    </div>

  );

};


export default App;


潇湘沐
浏览 145回答 2
2回答

慕森卡

这是因为 useState 是异步的,如果您想在更新后记录状态,您可以使用 useEffect 挂钩list作为依赖项另外我想建议为列表的每个元素添加一个键,一种快速的方法是使用数组索引,像这样:&nbsp;{list.map((item,index) => (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li key={index}>{item}</li>&nbsp; &nbsp; &nbsp; &nbsp; ))}但是最好将您的列表作为对象列表[value,id]并在您将项目添加到列表时生成一个 uuid()

桃花长相依

我将改写我的问题:我再次处理我的代码,一切似乎都正常,但是当我控制台记录数组列表时,数组第一个数组总是空的......import React, { useState } from "react";const App = () => {&nbsp; // State search et sa fonction de modification&nbsp; const [search, setSearch] = useState("");&nbsp; const updateSearch = (e) => {&nbsp; &nbsp; setSearch(e.target.value);&nbsp; &nbsp; console.log(search);&nbsp; };&nbsp; // State de liste et sa fonction de modification&nbsp; const [list, setList] = useState([]);&nbsp; const updateList = () => {&nbsp; &nbsp; setList([...list, search]);&nbsp; &nbsp; setSearch("");&nbsp; &nbsp; console.log(list);&nbsp; };&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <h1>Welcome on your todolist</h1>&nbsp; &nbsp; &nbsp; <br />&nbsp; &nbsp; &nbsp; <input type="text" onChange={updateSearch} value={search} />&nbsp; &nbsp; &nbsp; <button onClick={updateList}>enter</button>&nbsp; &nbsp; &nbsp; <h1>what is inside of list : {list}</h1>&nbsp; &nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; &nbsp; {list.map((item) => (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li>{item}</li>&nbsp; &nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; &nbsp; </ul>&nbsp; &nbsp; </div>&nbsp; );};export default App;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript