前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用redux做TODOLIST

使用redux做TODOLIST

作者头像
世间万物皆对象
发布2024-03-20 19:48:16
1000
发布2024-03-20 19:48:16
举报
文章被收录于专栏:startstart
store.js

代码语言:javascript
复制
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
代码语言:javascript
复制
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
代码语言:javascript
复制
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
代码语言:javascript
复制
export const ADDList = "ADDLIST";
export const DELLIST = "DELLIST";
todolist/_index.js
代码语言:javascript
复制
export const ADDList = "ADDLIST";
export const DELLIST = "DELLIST";
todolist.jsx
代码语言:javascript
复制
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;
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2024-03-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • store.js
  • todolist/redux/reducer.js
  • todolist/redux/todolist.js
  • todolist/redux/todoType.js
  • todolist/_index.js
  • todolist.jsx
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档