简体   繁体   English

我对 React 的 ToDoList 项目有一些问题

[英]I have some problem with ToDoList project by React

I am student, and i want to make a ToDoList with React.我是学生,我想用 React 制作一个 ToDoList。

I just want to make change when i submit or remove my schedule, but it doesn't working.我只想在提交或删除我的日程安排时进行更改,但它不起作用。

lists are not changed(not rendered as i want), but if i write something down in the submit box, it working!列表没有改变(没有按照我的意愿呈现),但是如果我在提交框中写下一些东西,它就可以工作了!

i can't figure out what is the problem.我不知道是什么问题。

Please Help!请帮忙!

(codes are so long and dirty i'm sorry this is my first question in stack overflow) (代码又长又脏,对不起,这是我在堆栈溢出中的第一个问题)

import { render } from "@testing-library/react";
import { months } from "moment";
import React, { createElement } from "react";
import { useState } from "react";
import styled from "styled-components";
import createRoot from 'react-dom';


const TodoInput=styled.input`
    font-size:22px;
    border:0;
    background:none;
    appearance:none;
    color:black;
    border-bottom:1px solid black;
    margin-bottom:20px;

`;

const TodoForm=styled.form`
    
`;
const TodoList=styled.ul`
    display:flex;
    flex-direction: column;
    
`;
const ToDoMem=styled.li`

`;

const ToDoContainer=styled.div`
    display:flex;
    flex-direction: column;
    align-items: center;
`;

const RemoveButton=styled.button`
    border:none;
    background-color: transparent;
    color:crimson;
`;

const ToDoList_KEY='ToDoList';

const listContainer=JSON.parse(localStorage.getItem(ToDoList_KEY)); 
let getToDoList=JSON.parse(localStorage.getItem(ToDoList_KEY));
function Todo()
{
    const [toDo,setToDo]=useState();
    const [toDoList,setToDoList]=useState([]);
    const [isScheduled,setIsScheduled]=useState(false);
    
    function preventerAndScheduled(event)
    {
        event.preventDefault();
        let getToDoList=JSON.parse(localStorage.getItem(ToDoList_KEY));
        if(getToDoList==null)
        {
            getToDoList=[];
            getToDoList.push(toDo);
            localStorage.setItem(ToDoList_KEY,JSON.stringify(getToDoList));
            return;
        }
         
        getToDoList.push(toDo);
        localStorage.setItem(ToDoList_KEY,JSON.stringify(getToDoList));
        
    }
    function submitted(event)
    {
        const newToDoObj={
            content: event.target.value,
            id: Date.now()
        }
        setToDo(newToDoObj);
        
    }
    
    function removeWhenClick (event)
    {
        const removeMem=event.target.id;
        let removeList=JSON.parse(localStorage.getItem(ToDoList_KEY));

        removeList=removeList.filter((mem)=>mem.id !== parseInt(removeMem));

        localStorage.setItem(ToDoList_KEY,JSON.stringify(removeList));
    }
   
    getToDoList=JSON.parse(localStorage.getItem(ToDoList_KEY));

    if(getToDoList==null)
    {
        return(
            <ToDoContainer>
                <TodoForm onSubmit={preventerAndScheduled}>    
                    <TodoInput onChange={submitted} type="text" placeholder="Schdule"/>
                </TodoForm>  
            </ToDoContainer>
            );
    }
    else
    {
        return(
            <ToDoContainer>
                <TodoForm onSubmit={preventerAndScheduled}>    
                    <TodoInput onChange={submitted} type="text" placeholder="Schdule"/>
                </TodoForm>
                <TodoList>
                {   
                    getToDoList.map((mem)=><ToDoMem key={mem.id}>{mem.content}
                    <RemoveButton 
                        id={mem.id}
                    onClick={removeWhenClick}>X</RemoveButton></ToDoMem>)
                    
                }
                </TodoList>
            </ToDoContainer>
            );
    }
   
     
    
}

export default Todo;

Your remove and add todo item handler functions had issues.您的删除和添加待办事项处理函数有问题。 They can be simplified like this.它们可以像这样简化。 Note that inside the callback functions we return the updated value for the component state and before that save the same representation to the local storage using the callback of setter method of useState hook:请注意,在回调函数中,我们返回组件状态的更新值,并在此之前使用useState钩子的 setter 方法的回调将相同的表示保存到本地存储:

  function preventerAndScheduled(event) {
    event.preventDefault();
    setToDoList((prevTodoList) => {
      const newTodoList = [...prevTodoList, toDo];
      localStorage.setItem(ToDoList_KEY, JSON.stringify(newTodoList));
      return newTodoList;
    });
  }

  function removeWhenClick(removeID) {
    setToDoList((prevTodoList) => {
      const newTodoList = prevTodoList.filter(({ id }) => removeID !== id);
      localStorage.setItem(ToDoList_KEY, JSON.stringify(newTodoList));
      return newTodoList;
    });
  }

It's always the better idea to use the callback function when updating states as we always get updated values (non-stale).在更新状态时使用回调函数总是更好的主意,因为我们总是得到更新的值(非陈旧的)。

You only need to load the items from local storage when component get mounted initially like below:您只需要在最初安装组件时从本地存储中加载项目,如下所示:

  const [toDoList, setToDoList] = useState(
    JSON.parse(localStorage.getItem(ToDoList_KEY)) || []
  );

Working Demo工作演示

编辑 xenodochial-panini-drkfrm

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

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