使用redux做TODOLIST

简介: 使用redux做TODOLIST

store.js



import { createStore, combineReducers } from 'redux';
import { reducer as todoReducer } from '../view/todolist/_index.js';
const reducer = combineReducers({
  todo: todoReducer,
})
export default createStore(reducer);


todolist/redux/reducer.js



import * as todoTypes from './todoType';
const reducer = (State = [], todo) => {
  const { type, data } = todo;
 switch (type) {
    case todoTypes.ADDList:
      const result = [
        data,
        ...State
      ]
      console.log(result)
      return result
    case todoTypes.DELLIST:
      State.splice(data, 1)
      return [...State]
    default:
      return State
  }
}
export default reducer


todolist/redux/todolist.js


import * as todoType from './todoType.js';
export const addList = (data) => ({ type: todoType.ADDList, data })
export const delList = (data) => ({ type: todoType.DELLIST, data })


todolist/redux/todoType.js


export const ADDList = "ADDLIST";
export const DELLIST = "DELLIST";


todolist/_index.js


export const ADDList = "ADDLIST";
export const DELLIST = "DELLIST";


todolist.jsx


import React, { useRef } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import * as actions from './redux/todolist'
import './todolist.css'
const View = () => {
  let ipt = useRef();
  const state = useSelector((state) => state)
  const dispath = useDispatch()
  //数据渲染
  const list = () => {
    return state.todo.map((value, index) => (
      <li key={index}>
        {index + 1}、{value}
        <button onClick={() => { delLists(index) }}>删除</button>
      </li>
    ))
  }
  //添加
  const addFn = () => {
    let val = ipt.current.value;
    dispath(actions.addList(val))
    ipt.current.value = ""
  }
  //删除
  const delLists = (index) => {
    dispath(actions.delList(index))
  }
  //回车添加
  const handleKeyUp = (e) => {
    let val = ipt.current.value;
    if (e.keyCode === 13) {
      dispath(actions.addList(val))
      ipt.current.value = ""
    }
  }
  return (
    <div className="todoBox">
      <h2>TODOLIST</h2>
      <input onKeyUp={handleKeyUp} ref={ipt} type="text" />
      <button onClick={addFn} >添加</button>
      {list()}
    </div>
  )
}
export default View;


相关文章
|
3月前
|
前端开发
hooks实现toDoList
使用React Hooks实现ToDoList应用,包括添加和删除待办事项功能,通过useState管理状态,并对输入进行唯一性校验以避免姓名重复。
35 4
|
2月前
|
存储 JavaScript 前端开发
|
存储 JavaScript 前端开发
【React】redux和React-redux
redux和React-redux
106 0
|
7月前
|
JavaScript 前端开发
React结合Redux实现Todolist
React结合Redux实现Todolist
53 0
|
7月前
|
资源调度 JavaScript 前端开发
React-Redux 对Todolist修改
React-Redux 对Todolist修改
47 0
|
JavaScript 中间件
React-Redux-thunk
React-Redux-thunk
50 0
|
存储 缓存 JavaScript
React | Redux的使用详解(一)
React | Redux的使用详解(一)
|
Web App开发 JavaScript 前端开发
React | Redux的使用详解(二)
React | Redux的使用详解(二)
|
存储 JavaScript 前端开发
React-Redux[上]
React-Redux[上]
81 0
|
JavaScript 前端开发 中间件
redux&react-redux(一)
redux&react-redux(一)
redux&react-redux(一)