React useReducer

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

React useReducer

月光晒了很凉快   2022-10-20 我要评论

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们