react 使用 @reduxjs/toolkit react-redux todoList 示例

该文章展示了如何在React应用中引入react-redux的Provider组件,将redux的store包裹在APP入口文件中,以便在各个页面都能访问到store。通过configureStore创建store,并用createSlice定义todos的reducer。组件通过useSelector和useDispatch钩子函数与store交互,实现添加、删除和切换Todo项的功能。
摘要由CSDN通过智能技术生成
  1. 引入 Provider 并包裹APP 入口文件,方便在每个页面都可以使用redux
import { Provider } from 'react-redux'
import store from './store'


// 渲染根组件App 到一个id为root 的dom 节点上
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <Provider store={store}>
    <App />
  </Provider>
)
  1. store/indexjs 文件
import { configureStore } from '@reduxjs/toolkit'
import todos from './tode'

// const modulesContext = require.context('./', false, /^(?!.*index\.js$).*\.js$/);
// // 从上下文中获取所有的模块,并将它们导入到一个对象中
// const modules = modulesContext.keys().reduce((modules, modulePath) => {
//   // 获取模块名
//   const moduleName = modulePath.replace(/^\.\/(.*)\.js$/, '$1');
//   // 导入模块
//   const value = modulesContext(modulePath);
//   modules[moduleName] = value.default
//   return modules;
// }, {});


const store = configureStore({
  reducer: {
  	// ...modules
    todos
  }
})
export default store
  1. todosjs 文件
import { createSlice } from '@reduxjs/toolkit'

const initialState = []

const todoSlice = createSlice({
  name: 'todos',
  initialState,
  reducers: {
    addTodo: (state,action) => {
      const { id, text} = action.payload
      state.push({ id, text, completed: false })
    },
    removeTodo: (state, action) => {
      return state.filter(todo => todo.id !== action.payload)
    },
    toggleTodo: (state, action) => {
      const index = state.findIndex(tode => tode.id === action.payload)
      if (index !== -1) {
        state[index].completed = !state[index].completed
      }
    }
  }
})
export const { addTodo, removeTodo, toggleTodo } = todoSlice.actions
export default todoSlice.reducer
  1. 组件中使用 todoList.js
import React, { useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { addTodo, removeTodo, toggleTodo } from '../../store/todos'
export default function TodoList() {
  const [inputValue, setInputValue] = useState('')
  const todos = useSelector(state => state.todos)
  const dispatch = useDispatch()
  const handleAdd = () => {
    dispatch(addTodo({
      id: Date.now(),
      text: inputValue
    }))
    setInputValue('')
  }
  const handleDel = (id) => {
    dispatch(removeTodo(id))
  }
  const handleToggle = (id) => {
    dispatch(toggleTodo(id))
  }
  return (
    <div>
      <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} />
      <button onClick={handleAdd}>Add</button>
      <ul>
        {
          todos.map(todo => (
            <li
              key={todo.id}
              style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}
              onClick={ () => handleToggle(todo.id) }
            >
              { todo.text }
              <button onClick={() => handleDel(todo.id)}>Delete</button>
            </li>
          ))
        }
      </ul>
    </div>
  )
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值