美文网首页
基于hook实现的全局状态管理

基于hook实现的全局状态管理

作者: skoll | 来源:发表于2020-06-19 10:22 被阅读0次

全局状态管理方式

1 .context

1 .以这种方式定义的全局变量其实可以把定义的参数和修改参数的函数都通过context传下来,其实可以满足小型项目的需求

2 .redux

3 .hook 实现全局

1 .参考 react-hooks-global-state
2 .他给的使用姿势好像有点问题
state.js
//定义全局变量并暴露接口

import {createGlobalState} from 'react-hooks-global-state'

const initialState = { count: 0,name:'libateer'};
// 定义初始全局数据

const { useGlobalState } = createGlobalState(initialState);
// 向外暴露接口

export default useGlobalState

//使用的地方
import React,{useState,usEffect} from 'react'
import useGlobalState from './redux'
//引入定义的全局变量

function Counter(){
    const [count, setCount] = useGlobalState('count');
//引用我们需要使用的全局变量和修改变量的方法
    const [name ,setName]=useGlobalState('name')

    return (
      <div>
         22<span>Counter: {count}</span> 
         <span>name: {name}</span>
        {/* update state by passing callback function */}
        <button onClick={() => setCount(v => v + 1)}>+1</button>
        {/* update state by passing new value */}
        <button onClick={() => setCount(count - 1)}>-1</button>
        <button onClick={() => setName("lala222")}>-1</button>
      </div>
    );
  };

export default Counter

简单版本

import React,{useState,useEffect} from 'react'

// const useGlobalState=(value)=>{
//     const [state,setState]=useState(value)
//     return [state,setState]
// }


// export default useGlobalState
// 这个不行,胎死腹中,这样别人引用的时候,仅仅是新建了一个实例,实际并没有共享一个变量
const createContainer = (initialState) => {
    let globalState = initialState;
    const listeners = Object.fromEntries(Object.keys(initialState).map(key => [key, new Set()]));
//每一个变量都需要定义个set结构,里面存储了所有引用这个变量的地方
  
    const setGlobalState = (key, nextValue) => {
      if(typeof nextValue==='function'){
        globalState = { ...globalState, [key]: nextValue(globalState[key]) };
      }else{
        globalState = { ...globalState, [key]: nextValue };
      }
      listeners[key].forEach(listener => listener());
    };
  
    const useGlobalState = (key) => {
      const [state, setState] = useState(globalState[key]);
//这个函数每次调用一次,就是有一个新的地方使用了这个变量,就给这个变量的set结构里面新加一个setState的函数接口,这样其他任何地方修改的时候,都会触发这个变量里面所有的setState接口,让所有的变量都发生变化。并不是set一份,其他的就会自动变得
      useEffect(() => {
        const listener = () => {
          setState(globalState[key]);
        };
        listeners[key].add(listener);
        listener(); // in case it's already changed
        return () => listeners[key].delete(listener); // cleanup
      }, []);
      return [state, (nextValue) => setGlobalState(key, nextValue)];
    };
  
    return {
      setGlobalState,
      useGlobalState,
    };
  };
export default createContainer

1 .使用

import React,{useState,usEffect} from 'react'
import useGlobalState  from './redux'

function Counter(){
    const [name,setName]=useGlobalState('count')
    console.log(name)

    return (
      <div>
        {name}
        <button onClick={() => setName(10)}>+1</button>
        
      </div>
    );
  };

export default Counter

相关文章

网友评论

      本文标题:基于hook实现的全局状态管理

      本文链接:https://www.haomeiwen.com/subject/qteuxktx.html