使用redux完成一个简单版的todoList

首先安装好所需要的插件 

redux

react-redux

然后在main.jsx中写入代码

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";

import { Provider } from "react-redux";
import { legacy_createStore } from "redux";

const initialState = {
  todo: [],
};

function reducer(state = initialState, action) {
  let { type, args } = action;
  let todo = null;
  switch (type) {
    case "ADD_TODO":
      // 新增
      todo = [...state.todo];
      todo.push(args);
      return { ...state,todo };
    case "UPDATE_TODO":
      // 更新
      todo = [...state.todo];
      todo[args].isfinish=!todo[args].isfinish;
      return { ...state,todo };
    case "DEL_TODO":
      // 移除
      todo = [...state.todo];
      todo.splice(args,1);
      return { ...state,todo };

    default:
      return state;
  }
}

const store = legacy_createStore(reducer);

ReactDOM.createRoot(document.getElementById("root")).render(
  <>
    
      
    
  
);

App.jsx中写入代码

import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
const App = () => {
  let [value, setValue] = useState("");
  let todo = useSelector(state => state.todo);
  let dispatch = useDispatch();
  // input受控
  function changeInp(e) {
    setValue(e.target.value);
  }
  // 点击添加按钮
  let add = () => {
    dispatch({
      type: "ADD_TODO",
      args: { name: value, time: Date.now(), isfinish: false },
    });
  };
  // 复选框受控
  let changeBox=(index)=>{
    dispatch({
      type: "UPDATE_TODO",
      args: index,
    });
  }
  // 删除操作
  let remove=(index)=>{
    dispatch({
      type: "DEL_TODO",
      args: index,
    });
  }
  return (
    <>
      
事项共:{todo.length}个

未完成事项:

    {todo.map((item, index) => { if (!item.isfinish) return (
  • {item.name} {item.time}
  • ); })}

已完成事项:

    {todo.map((item, index) => { if (item.isfinish) return (
  • {item.name} {item.time}
  • ); })}
); }; export default App;

css样式自己书写

你可能感兴趣的:(javascript,前端,react.js)