简体   繁体   中英

I have some problem with ToDoList project by React

I am student, and i want to make a ToDoList with React.

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:

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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