广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >ReactuseReducer终极使用教程
  • 263
分享到

ReactuseReducer终极使用教程

ReactuseReducerReactuseReducer使用方式 2022-11-13 18:11:04 263人浏览 薄情痞子
摘要

目录1. 概述2. useReducer使用3. 使用useReducer完成todolist列表功能1. 概述 useReducer 这个 Hooks 在使用上几乎跟 Redux

1. 概述

useReducer 这个 Hooks 在使用上几乎跟 Redux 一模一样,唯一缺点的就是无法使用 redux 提供的中间件

使用 hook 函数后,一般情况下,一个组件组中的数据我们可以用 useReducer 来管理,而不是用 redux 来完成,redux 一般存储公用数据,而不是把所有的数据都存储在里面,redux 它是一个单一数据源,如果存储多个数据的话,性能会降低。

2. useReducer使用

import React, { useReducer } from 'react'
// useReducer 它就是一个小型的redux,它几乎和redux是一样的,也可以管理数据
// 初始化数据
const initState = {
  count: 100
}
// reducer纯函数中的state无需在定义函数时指定初始值,initState 会赋值给 reducer
// const reducer = (state,action)=>{}
// type, payload 是从 action 中结构出来的
const reducer = (state, { type, payload }) => {
  if (type === 'add') {
    return { ...state, count: state.count + payload }
  }
  return state
}
const App = () => {
  // state 它就是初始化后数据的对象,状态
  // dispatch 它就是用来发送指令让reducer来修改state中的数据
  // reducer它就是一个纯函数,用来修改initState初始化后数据状态函数
  // initState 初始化数据
  const [state, dispatch] = useReducer(reducer, initState)
  const addCount = () => {
    // 数据以改变就会触发 useReducer 中的 reducer 函数
    dispatch({ type: 'add', payload: 2 })
  }
  return (
    <div>
      <h3>App组件 -- {state.count}</h3>
      <button onClick={addCount}>++++</button>
    </div>
  );
}
export default App;

useReducer 的惰性初始化:

import React, { useReducer } from 'react'
const initState = {
  count: 100
}
const reducer = (state, { type, payload }) => {
  if (type === 'add') {
    return { ...state, count: state.count + payload }
  }
  return state
}
const App = () => {
  // initState 初始化数据
  // 如果useReducer它有第3个参数,则第2个参数就没有意义,它以第3个参数优先,第3个参数,惰性初始化,提升性能
  // 第3参数它是一个回调函数且一定要返回一个对象数据,当然你也可以直接返回一个值也可以,不建议
  const [state, dispatch] = useReducer(reducer, null, () => ({ count: 2000 }))
  const addCount = () => {
    dispatch({ type: 'add', payload: 2 })
  }
  return (
    <div>
      <h3>App组件 -- {state.count}</h3>
      <button onClick={addCount}>++++</button>
    </div>
  );
}
export default App;

注意:惰性初始化可以提升性能,惰性初始化使得数据不会在一开始就进行初始化,而是在使用的时候再进行初始化。

3. 使用useReducer完成todolist列表功能

reducer.js

// 导出初始化数据
export const initState = {
  // 任务列表数据源
  todos: []
}
// 导出用于操作当前todos任务列表的纯函数
export const reducer = (state, { type, payload }) => {
  // [...state.todos, payload] 追加数据
  if ('add' === type) return { ...state, todos: [...state.todos, payload] }
  if ('del' === type) return { ...state, todos: state.todos.filter(item => item.id != payload) }
  return state
}

父组件(App.jsx):

import React from 'react';
import Todo from './Todo';
const App = () => {
  return (
    <div>
      <Todo />
    </div>
  );
}
export default App;

ToDo组件:

import React, { useReducer } from 'react'
import FORM from './components/Form'
import List from './components/List'
// 导入 reducer 文件中的初始化数据和操作数据函数
import { initState, reducer } from './reducer'
const Todo = () => {
  const [{ todos }, dispatch] = useReducer(reducer, initState)
  return (
    <div>
      {}
      <Form dispatch={dispatch} />
      {}
      <List dispatch={dispatch} todos={todos} />
    </div>
  )
}
export default Todo

表单项组件:

import React from 'react'
// 表单项组件
const Form = ({ dispatch }) => {
  // 回车事件
  const onEnter = evt => {
    if (evt.keyCode === 13) {
      const title = evt.target.value.trim()
      // todo每项中的数据
      const todo = {
        id: Date.now(),
        title,
        done: false
      }
      dispatch({ type: 'add', payload: todo })
      evt.target.value = ''
    }
  }
  return (
    <div>
      <input onKeyUp={onEnter} />
    </div>
  )
}
export default Form

任务项组件:

import React from 'react'
// 任务项组件
const List = ({ todos, dispatch }) => {
  const del = id => {
    dispatch({ type: 'del', payload: id })
  }
  return (
    <div>
      <h3>任务项</h3>
      <hr />
      <ul>
        {todos.map(item => (
          <li key={item.id}>
            <span>{item.title}</span>
            <span onClick={() => del(item.id)}>删除</span>
          </li>
        ))}
      </ul>
    </div>
  )
}
export default List

到此这篇关于React useReducer终极使用教程的文章就介绍到这了,更多相关React useReducer内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: ReactuseReducer终极使用教程

本文链接: https://www.lsjlt.com/news/169610.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作