LocalStorage并在待办事项应用程序中使用Reducer

时间:2020-07-14 21:19:48

标签: reactjs

我需要在待办事项列表中添加本地存储功能,通常可以对useState进行此操作,现在我尝试使用useReducer,并且混淆了如何以及在何处将功能最好地放入代码中。谢谢< / p>

import React, { useReducer, useState, useEffect } from 'react';
    
    const todoReducer=(state,action)=>{
    
      switch(action.type)
      {
        case('add-item'):
        return {todo: [...state.todo,{text:action.text,priority:action.priority,isCompleted:false,isEditing:false}]};
        case('isCompletedChange'):
        return {todo: state.todo.map((item,idx)=>idx===action.idx?{...item,isCompleted:!item.isCompleted}:item)};
        case('delete'):
        return {todo: state.todo.filter((item,idx)=>idx===action.idx?null:item)};
        case('edit'):
        return {todo: state.todo.map((item,idx)=>idx===action.idx?{...item,isEditing:!item.isEditing}:{...item,isEditing:false})};
        case('edited'):
        return {todo: state.todo.map((item,idx)=>idx===action.idx?{...item,text:action.text}:item)};
      }
    }
    function App()
    {
    const [{todo},setTodo]=useReducer(todoReducer,{todo:[]})
    const [newItem,setNewItem]=useState({
      text:"",
      priority:"normal"
    })
    
    const newItemHandler=(e)=>{
    const {value,name}=e.target;
    setNewItem({...newItem,[name]:value})
    }
    const editingMode=(e,idx)=>{
    if(e.key==="Enter")
    {
      setTodo({type:'edited',text:e.target.value,idx:idx})
      setTodo({type:'edit',idx})
    }
    }
    return(
      <section>
      <form  onSubmit={(e)=>{e.preventDefault();setTodo({type:'add-item',text:newItem.text,priority:newItem.priority})}}>
        <h1>{newItem.text}</h1>
        <h1>{newItem.detail}</h1>
        <input value={newItem.text} name="text" onChange={newItemHandler}></input>
        <select value={newItem.priority} name="priority" onChange={newItemHandler}>
          <option value="high">high</option>
          <option value="normal">normal</option>
          <option value="low">low</option>
        </select>
        <input type="submit" value="add"></input>
      </form>
        <div>
          <table>
        <thead>
          <tr>
          <th>note</th>
          <th>priority</th>
          <th></th>
          <th></th>
          </tr>
        </thead>
         <tbody>
         {todo.map((item,idx)=>(
            <tr> 
              <td>{!item.isEditing?item.text:<input onKeyUp={(e)=>editingMode(e,idx)}></input>} </td>    
              <td>{item.priority} </td>  
              <td style={{color:item.isCompleted?"red":"black"}} onClick={()=>setTodo({type:'isCompletedChange',idx:idx})}>✔</td>
              <td onClick={()=>setTodo({type:'delete',idx})}>✖</td>  
              <td onClick={()=>setTodo({type:'edit',idx})}>✏</td>  
            </tr>
          ))}
         </tbody>
        </table>
        </div>
      </section>
    )
    }
    export default App;

我需要在待办事项列表中添加本地存储功能,通常可以对useState进行此操作,现在我尝试使用useReducer,并且混淆了如何以及在何处将功能最好地放入代码中。谢谢< / p>

0 个答案:

没有答案