简体   繁体   English

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

[英]TodoList using useState and React - Problem updating the todoList

I have a problem updating my todoList using React and useState... Should I try using "push" or something different to update my list?我在使用 React 和 useState 更新我的 todoList 时遇到问题...我应该尝试使用“推送”还是其他方式来更新我的列表?

thank you very much !!非常感谢您 !!

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;

I will rephrase my question: I worked on my code again and everything seems to work but when I console log the array list, the array first array is always empty...我将重新提出我的问题:我再次处理我的代码,一切似乎都正常,但是当我控制台记录数组列表时,数组第一个数组总是空的......

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]);
    setSearch("");
    console.log(list);
  };

  return (
    <div>
      <h1>Welcome on your todolist</h1>
      <br />
      <input type="text" onChange={updateSearch} value={search} />
      <button onClick={updateList}>enter</button>
      <h1>what is inside of list : {list}</h1>

      <ul>
        {list.map((item) => (
          <li>{item}</li>
        ))}
      </ul>
    </div>
  );
};

export default App;

it's because useState is asynchronous, if you want to log the state after updating it you can use useEffect hook with list as a dependency这是因为 useState 是异步的,如果你想在更新 state 后记录它,你可以使用 useEffect 钩子和list作为依赖项
Also I would like recommend adding a key to each element of your list, a quick way to do it is to use the array index, like this:另外,我建议为列表的每个元素添加一个键,一种快速的方法是使用数组索引,如下所示:

 {list.map((item,index) => (
          <li key={index}>{item}</li>
        ))}

But it will be better to have your list as a list of object [value,id] and generate an uuid() when you add items to your list但是最好将您的列表作为 object [value,id]的列表并在您将项目添加到列表时生成一个 uuid()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM