简体   繁体   English

我正在尝试使用 React useState 挂钩更新 state? 创建读取和删除部分已完成,但我无法更新

[英]I am trying to update the state using the React useState hook?? The Create Read and Delete part has been done but iam not able to update

I am making a To Do App using useState react hook.我正在使用 useState 反应钩子制作一个待办事项应用程序。 I have complete with Create Read and Delete parts but I have not been able to update the state.我已完成创建读取和删除部分,但我无法更新 state。 Can somebody please help me.有人能帮帮我吗。 I have complete the same with Class component.我已经完成了与 Class 组件相同的操作。

/****************************** MY app.js file ********************************************/ /****************************** 我的 app.js 文件 ************** ******************************/

import React, { useState } from "react";
import "./App.css";
import ToDoList from "./Components/ToDoList";

function App() {
  const [change, handleChange] = useState("");
  const [items, addItem] = useState([]);

  let handleSubmit = (e) => {
    e.preventDefault();
    // console.log(change)
    if (change !== "") {
      addItem([...items, { text: change, key: Date.now() }]);
      handleChange("");
    }
  };

  let removeTask = (key) => {
    let item = items.filter((ele) => {
      return ele.key !== key;
    });
    console.log(item);
    addItem([...item]);
  };

  let updateToDo = (value, key) => { // <<<<<<< I need to make changes in this piece of code.
    let allItem = items.map((e) => {
      if (e.key === key) {
        e.text = value;
      }
      console.log(...allItem);
      // addItem([...items, { allItem }]);
    });
  };

  return (
    <div className="toDoContainer">
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          onChange={(e) => handleChange(e.target.value)}
          value={change}
          placeholder="Add Item"
        />
        <button>Add Item</button>
      </form>
      <ToDoList items={items} removeTask={removeTask} updateToDo={updateToDo} />
    </div>
  );
}

export default App;


/*************************************** My ToDoList.js *************************************/

import React from "react";
import "./ToDoList.css";

function ToDoList({ items, removeTask, updateToDo }) {
  let toDoItems = items.map((item) => {
    return (
      <div className="toDoItems" key={item.key}>
        <p>
          <input
            type="text"
            id = {item.key}
            value={item.text}
            onChange={(e) => updateToDo(e.target.value, item.key)}
          />

          <span onClick={() => removeTask(item.key)}>&#10008;</span>
        </p>
      </div>
    );
  });
  return <div>{toDoItems}</div>;
}

export default ToDoList;

You can map items into new array and when the item key matches the key parameter update the text property.您可以将 map 项目放入新数组中,并在项目键与键参数匹配时更新文本属性。

let updateToDo = (value, key) => {
  const allItem = items.map(item => {
    const newItem = {...item};
    if (item.key === key) {
      newItem.text = value;
    }
    return newItem;
  });
  console.log(...allItem);
  addItem(allItem);
};

buddy!伙伴!

First fo all, I suggest you can read document about React Hooks , it have clear explain how to update State when you using useState , I split several parts below:首先,我建议你可以阅读有关 React Hooks 的文档,它清楚地解释了当你使用useState时如何更新 State,我在下面拆分了几个部分:

On here const [items, addItem] = useState([]);在这里const [items, addItem] = useState([]); , The Hooks useState will return a array, the first item is your value of state, at this time is a empty array [] , the second item is a method which can update value of state. , Hooks useState会返回一个数组,第一项是你的 state 的值,此时是一个空数组[] ,第二项是一个可以更新 state 值的方法。

Next, in your update method updateToDo , you used map to update original value of state and create the new value of state.接下来,在您的更新方法updateToDo中,您使用map更新 state 的原始值并创建 state 的新值。 so why didn't you call addItem to update your value of state?(Maybe you tried, but I have no idea for why you comment out that line?)那么你为什么不调用addItem来更新你的 state 的值呢?(也许你试过了,但我不知道你为什么注释掉那行?)

You just need to pass new value of state for addItem , and I suggest you can rename it to setItem instead of addItem .您只需将 state 的新值传递给addItem ,我建议您可以将其重命名为setItem而不是addItem

You can following:你可以关注:

let updateToDo = (value, key) => { // <<<<<<< I need to make changes in this piece of code.
  let allItem = items.map((e) => {
    if (e.key === key) {
      e.text = value;
    }
    addItem(allItem);
  });
};

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

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