简体   繁体   English

修改元素时更新 useState() 数组 REACT

[英]update useState() array when element is modified REACT

I am fairly new to react to please bare with me.我是相当新的反应,请与我裸露。 I am creating a todo application that just keeps tracks of tasks.我正在创建一个只跟踪任务的待办事项应用程序。

Issue:问题:

the state called [tasks, setTasks] = useState([]) does update when i try to edit a task within the tasks state.当我尝试在tasks状态中编辑任务时[tasks, setTasks] = useState([])名为[tasks, setTasks] = useState([])会更新。

For example lets say tasks contains ["make bed", "fold cloths"] and I wanted to update "fold cloths" to "fold clothes and put away".例如,假设tasks包含["make bed", "fold cloths"]整理["make bed", "fold cloths"] ,我想将“折叠布”更新为“折叠衣服并收起”。 When I use setTasks the state does not update.当我使用setTasks ,状态不会更新。

The modification of the state happens in the modifyTask function.状态的修改发生在modifyTask函数中。

Here is my code:这是我的代码:

import React, { useEffect, useState } from "react";

// Imported Components below
import CurrentTasks from "./CurrentTasks";

function InputTask() {
  // Initial array for storing list items
  // Tracking state of input box
  const [task, setTask] = useState("");
  const [tasks, setTasks] = useState(
    JSON.parse(localStorage.getItem("tasks") || "[]")
  );

  function deleteTask(index) {
    function checkIndex(task, i) {
      if (i !== index) {
        return task;
      }
    }
    setTasks(prev => prev.filter(checkIndex));
  }

  function modifyTask(index) {
    let editedTask = prompt("Please edit task here..", tasks[index]);
    function editTask(task, i) {
      if (i === index) {
        task = editedTask;
      }
      console.log(task);
      return task;
    }
    setTasks(prev => prev.filter(editTask));
  }

  function handleAddTask() {
    setTasks(prev => prev.concat(task));
  }

  useEffect(() => {
    // Saves every time tasks state changes
    localStorage.setItem("tasks", JSON.stringify(tasks));
    console.log("Tasks: " + tasks);
    setTask("");
  }, [tasks]);

  return (
    <div className="container">
      <div className="input-group mt-4">
        <input
          type="text"
          value={task}
          onChange={e => setTask(e.target.value)}
          className="form-control form-control-lg"
          placeholder="Write task here..."
        />
        <div className="input-group-append">
          <button onClick={handleAddTask} className="btn btn-outline-secondary">
            Add
          </button>
        </div>
      </div>
      <CurrentTasks
        allTasks={tasks}
        deleteTask={deleteTask}
        modifyTask={modifyTask}
      />
    </div>
  );
}

export default InputTask;

What I think is happening我认为正在发生的事情

-> My theory is that the state only updates when the number of elements within the array changes. -> 我的理论是,只有当数组中的元素数量发生变化时,状态才会更新。 If thats the case is there an elegant way of doing so?如果是这样的话,有没有一种优雅的方式来做到这一点?

在此处输入图片说明

You just need to change your modify function to use map instead of filter , as filter doesn't change the array outside of removing elements.您只需要更改修改函数以使用map而不是filter ,因为filter在删除元素之外不会更改数组。 Map takes the returned values and creates a new array from them. Map 获取返回的值并从中创建一个新数组。

  function modifyTask(index) {
    let editedTask = prompt("Please edit task here..", tasks[index]);
    function editTask(task, i) {
      if (i === index) {
        task = editedTask;
      }
      console.log(task);
      return task;
    }
    setTasks(prev => prev.map(editTask));
  }

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

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