带你一起手写useReducer

简介: 带你一起手写useReducer

useReducer是基于redux的思想,同时也是useState的替代方案。

原生useReducer的特点

  1. 接收两个参数,第一个参数是reducer函数,第二个参数是一个初始的状态值。
  2. useReducer返回的是一个数组,数组的第一个元素是存储的状态,第二个元素是触发action的方法。

更多更详细的关于useReducer的用法,请看我的这篇博客需要掌握的Hooks之useReducer与useContext

手写useReducer

实现useReducer需要注意的几点:

  1. reducer函数和初始的状态值是用户自定义的。
  2. reducer函数接受两个参数分别是state和action。
  3. useReducer函数接收用户自定以得reducer函数和初始的状态值。
  4. 在useReducer函数中调用到了useState这个钩子函数。

第一步:使用useState获取到用户传递的初始状态值

const [state,setState] = useState(initialState);
复制代码

第二步:通过setState执行用户dispatch过来的action

let dispatch = (action) => {
    setState(reducer(state,action))
}
复制代码

第三步:返回一个数组数组的第一个参数是状态值,第二个状态值是设置这个状态的方法

return [state,dispatch]
复制代码

完整实现

import React,{useState} from 'react'
import ReactDOM from 'react-dom'
/**
 * @description: 手写useReducer 
 * @param {*}
 * @return {*}
 */
function useReducer(reducer,initialState) {
    const [state,setState] = useState(initialState);
    let dispatch = (action) => {
        setState(reducer(state,action))
    }
    return [state,dispatch]
}
function App() {
    const reducer = (state,action) => {
        switch (action.type) {
            case 'increment':
                return state + 1;
            case 'decrement':
                return state - 1;
            default:
                return state;
        }
    }
    const [count,dispatch] = useReducer(reducer,0)
    return (
        <>
            <h1>当前求和为:{count}</h1>
            <button onClick={() => dispatch({type: 'increment'})}>点我+1</button>
            <button onClick={() => dispatch({type: 'decrement'})}>点我-1</button>
        </>
    )
}
ReactDOM.render(<App />, document.querySelector('#root'));
复制代码

在线实现

值得深思的问题

  • 通过实现useReducer我们可以看出这和redux中的reducer的实现思想是一样的,编程思想有时候即使在不同的应用场景中却有着共同的实现思想。
  • 准确理解useReducer的关键是理解useReducer中state的流动过程。
目录
打赏
0
0
0
0
6
分享
相关文章
手写一个防抖
手写一个防抖
53 0
10分钟教你手写8个常用的自定义hooks
Hook 是 React 16.8 的新增特性。它可以让你在不编写 class 的情况下使用 state 以及其他的 React 特性。本文是一篇以实战为主的文章,主要讲解实际项目中如何使用hooks以及一些最佳实践,不会一步步再介绍一遍react hooks的由来和基本使用,因为写hooks的文章很多,而且官网对于react hooks的介绍也很详细,所以大家不熟悉的可以看一遍官网。
535 0
手写vue3核心源码——响应式原理(Computed篇)
手写vue3核心源码——响应式原理(Computed篇)
react手写全选反选
react手写全选反选
111 0
react手写全选反选
前端学习笔记202306学习笔记第四十六天-vue-手写观察者模式4
前端学习笔记202306学习笔记第四十六天-vue-手写观察者模式
89 0
实战:从 Redux 中的代码片段中应用柯里化!
柯里化(Currying):是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数、返回最终结果的新函数的技术。
简单手写实现react的函数组件
简单手写实现react的函数组件
187 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等