简体   繁体   English

在反应中使用 useState 钩子时如何读取更新数组的值?

[英]How to read the value of updated array while using useState hook in react?

I am trying to build my 1st ToDo-list-app in React & I can't seem to successfully read the data from my "list" array which I've initiated using useState([]).我正在尝试在 React 中构建我的第一个 ToDo-list-app & 我似乎无法成功地从我使用 useState([]) 启动的“列表”数组中读取数据。 The issue I'm facing is - if my 1st entered task is "1-Eat Breakfast" & I click on the add button, I'm getting an empty array in console.log, When I enter my 2nd task lets say - "2-Hit the gym";我面临的问题是 - 如果我第一个输入的任务是“1-Eat Breakfast”并且我点击添加按钮,我在 console.log 中得到一个空数组,当我输入我的第二个任务时让我们说 - “ 2-去健身房”; that's when my previous task is getting console logged.那是我之前的任务是记录控制台的时间。 So, apparently I am unable to read the latest state of my array - "list".所以,显然我无法读取数组的最新 state - “列表”。 Can you please point out what I am doing wrong in the code given below?你能指出我在下面给出的代码中做错了什么吗? Thanks a lot.非常感谢。

import { useState } from "react";

const ToDo = () => {
  const [task, setTask] = useState("");
  const [list, setList] = useState([]);

  const readData = (event) => {
    event.preventDefault();
    setTask(event.target.value);
  };

  const showList = (event) => {
    event.preventDefault();
    setList([...list, task]);
    console.log(list);
  };

  return (
    <div>
      <div>
        <form onSubmit={showList}>
          <input type="text" value={task} onChange={readData} />
          <button>Add to List</button>
        </form>
      </div>
    </div>
  );
};

export default ToDo;

can you change你能改变吗

 const showList = (event) => {
    event.preventDefault();
    setList([...list, task]);
    console.log(list);
  };

to

 const showList = (event) => {
    event.preventDefault();
    list.push(task);
    setList(list);
    console.log(list);
  };

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

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