react js自定义实现状态管理

news/2024/7/15 18:07:20 标签: 前端, javascript, 服务器, react, react.js

redux基础实现

myRedux

javascript">export const createStore = (reduce) => {
  if (typeof reduce !== 'function') throw new Error('Expected the reducer to be a function.')
  let state,
    listeners = []
  state = reduce()


  const getState = () => state
  const dispatch = (action) => {
    if(typeof action !== 'object' || typeof action.type !== 'string') throw new Error('Actions must be plain objects.')
    state = reduce(state, action)
    listeners.forEach(listener => listener())
  }
  const subscribe = (listener) => {
    if(typeof listener !== 'function') throw new Error('Expected the listener to be a function.')
    listeners.push(listener)
    return () => listeners = listeners.filter(l => l !== listener)
  }

  return {
    getState,
    dispatch,
    subscribe,
  }
}

 

使用

javascript">import React, { useEffect, useState } from 'react'
import { createStore } from './myRedux'


const reduce = (state = { a: 123 }, action = {}) => {
  state = { ...state }
  switch (action.type) {
    case 'tset':
      state.a = Math.random() * 1000
      return state
    default:
      return state
  }

}
const store = createStore(reduce)



export default function Test() {
  const state = store.getState()
  const [_, foceUpdate] = useState(0)
  useEffect(() => {
    store.subscribe(() => {
      foceUpdate(Date.now())
    })
  }, [])
  const change = () => {
    store.dispatch({ type: 'tset' })
  }
  return (
    <div>
      <h1>Test {state.a}</h1>
      <button onClick={change} >change</button>
    </div>
  )
}

 

模仿pinia方式管理

myPinia.js

javascript">export const createStore = (f) => {
  if (typeof f !== 'function') throw new Error('Expected a function')
  const state = f()
  watch(state)
  const proxy = new Proxy(state, {
    get: (target, prop) => {
      const v = target[prop]
      const isState = v instanceof StoreState
      return isState ? v.value : v
    },
    set: () => state,
  })
  const userStore = () => {
    return proxy
  }

  return userStore
}

const watch = (obj) => {
  Object.keys(obj).forEach((key) => {
    const storeState = obj[key]
    if (storeState instanceof StoreState) {
      let value = storeState.value
      Object.defineProperty(storeState, 'value', {
        get: () => value,
        set: (newValue) => {
          value = newValue
          updateView()
        },
      })
    }
  })
}

class StoreState {
  constructor(value) {
    this.value = value
  }
}

export const useStoreState = (value) => {
  return new StoreState(value)
}
let listeners = []
const updateView = () => listeners.forEach((f) => f())
export const subscribe = (f) => {
  if (typeof f !== 'function') throw new Error('Expected a function')
  if (!listeners.includes(f)) listeners.push(f)
  return () => (listeners = listeners.filter((l) => l !== f))
}

使用

javascript">import React, { useEffect, useState } from 'react'
import { createStore, useStoreState, subscribe } from './myPinia'

const userStore = createStore(() => {
  let a = useStoreState(123)
  const change = () => {
    a.value++
  }
  return { a, change }
})

export default function Test() {
  const [_, forceUpdate] = useState(0)
  useEffect(() => {
    subscribe(() => forceUpdate(Date.now()))
  }, [])
  const store = userStore()
  const change = () => {
    store.change()
    console.log(store.a);
  }
  return (
    <div>
      <h1>test {store.a}</h1>
      <button onClick={change} >change</button>
    </div>
  )
}

不足的是,还是需要forceUpdate

 


http://www.niftyadmin.cn/n/5325463.html

相关文章

29 旋转工具箱

效果演示 实现了一个菜单按钮的动画效果&#xff0c;当鼠标悬停在菜单按钮上时&#xff0c;菜单按钮会旋转315度&#xff0c;菜单按钮旋转的同时&#xff0c;菜单按钮旋转的8个小圆圈也会依次旋转360度&#xff0c;并且每个小圆圈的旋转方向和菜单按钮的旋转方向相反&#xff0…

解锁 JavaScript 数组的强大功能:常用方法和属性详解(上)

&#x1f90d; 前端开发工程师&#xff08;主业&#xff09;、技术博主&#xff08;副业&#xff09;、已过CET6 &#x1f368; 阿珊和她的猫_CSDN个人主页 &#x1f560; 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 &#x1f35a; 蓝桥云课签约作者、已在蓝桥云…

C#灵活的任务调度组件FluentScheduler

FluentScheduler是一个C#的灵活的任务调度组件&#xff0c;支持各类任务调度。网上有很多演示代码&#xff0c;此处记录下来&#xff0c;方便自己查找。 // See https://aka.ms/new-console-template for more information //Console.WriteLine("Hello, World!");us…

14. 接口(适配器设计模式)

接口 接口1. 定义格式2. 成员特点2.1 成员方法2.2 默认方法2.3 静态方法2.4 变量 3. 接口的实现3.1 实现规则3.2 实现格式3.2.1 单实现格式3.2.2 多实现格式 3.3 接口的继承3.3.1 接口与类的继承3.3.2 接口与接口的继承 4.类与接口的区别5. 注意事项 适配器设计模式 接口 接口…

【数据结构】八大排序之计数排序算法

&#x1f984;个人主页:修修修也 &#x1f38f;所属专栏:数据结构 ⚙️操作环境:Visual Studio 2022 目录 一.计数排序简介及思想 二.计数排序代码实现 三.计数排序复杂度分析 &#x1f4cc;时间复杂度 &#x1f4cc;空间复杂度 结语 一.计数排序简介及思想 计数排序(Cou…

Python数据的处理

一.字符串拼接的几种方式 使用str.join()方法进行拼接字符串直接拼接使用格式化字符串进行拼接 ​ s1hello s2world #(1)使用➕进行拼接 print(s1s2) #(2)使用字符串的join&#xff08;&#xff09;方式 print(.join([s1,s2])) print(*.join([s1,s2])) print(你好.join([s1,s…

春节回家前,请一定给你的电脑装上KKView远程控制软件

马上春节了&#xff0c;电脑不能带回家&#xff0c;有时候要处理点意外的事情&#xff0c;怎么办&#xff1f;只要走之前&#xff0c;给你电脑装上KKView远程控制软件&#xff0c;就可以随时随地用手机或电脑控制你的工作电脑&#xff0c;远程办公、传文件、看摄像头都没问题。…

机器人制作开源方案 | 乒乓球自动拾取机器人

作者&#xff1a;刘众森、王森、王绘东、崔岳震、宋维鑫 单位&#xff1a;山东农业工程学院 指导老师&#xff1a;潘莹月、廖希杰 1. 场景调研 我们小组选择项目的任务方向乒乓球的捡取与存放&#xff0c;针对此问题我们研发了一款乒乓球自动拾取机器人。众所周知&#xff0…