第52节——useSyncExternalStore封装一个简版的redux——了解

一、前言

Concurrent 模式是 React18 中最引人瞩目的新特性。通过使用 useTransition、useDeferredValue,更新对应的 reconcile 过程变为可中断,不再会因为长时间占用主线程而阻塞渲染进程,使得页面的交互过程可以更加流畅。不过这种新特性,在给我们带来用户体验提升的同时,也给我们带来了新的挑战。在我们使用诸如 redux、mobx 等第三方状态库时,如果开启了 Concurrent 模式,那么就有可能会出现状态不一致的情形,给用户带来困扰。针对这种情况, React18 提供了一个新的 hook - useSyncExternalStore,来帮助我们解决此类问题。

useSyncExternalStore 这个 hook 并不是给我们在日常项目中用的,它是给第三方类库如 Redux、Mobx 等内部使用的

二、基本使用

useSyncExternalStore 是一个新的钩子,它通过强制的同步状态更新,使得外部 store 可以支持并发读取。它实现了对外部数据源订阅时不在需要 useEffect,并且推荐用于任何与 React 外部状态集成的

此方法返回存储的值并接受三个参数:

subscribe:用于注册一个回调函数,当存储值发生更改时被调用。

getSnapshot: 返回当前存储值的函数。

getServerSnapshot:返回服务端渲染期间使用的存储值的函数

const state = useSyncExternalStore(subscribe, getSnapshot[, getServerSnapshot]);

三、基于useSyncExternalStore封装一个redux

1、创建createReducerStore.js

/**
 * 
 * @param {*} reducer 
 * 当前的reducer函数,用于更新state返回
 * 
 * @param {*} initialState 
 * 初始值状态
 * @returns 
 */
const createReducerStore = (reducer, initialState) => {
  let state = initialState;
  // 数据改变的监听器
  const listeners = new Set();

  // 获取当前状态
  const getSnapshot = () => state;

  // 调用dispatch改变state
  const dispatch = (action) => {
    // reducer 改变state
    state = reducer(state, action);
    // 通知视图重新渲染
    listeners.forEach((listener) => listener());
  };

  /**
   * 每次dispatch出发
   * @param {} listener 
   * 添加一个监听器
   * @returns 
   */
  const subscribe = (listener) => {
    listeners.add(listener);
    // 卸载简单,删除监听器
    return () => {
      listeners.delete(listener);
    };
  };
  return {
    getSnapshot,
    dispatch,
    subscribe,
  };
};
export default createReducerStore;

2、创建useReducerStore

import { useSyncExternalStore } from "react";
import createReducerStore from "./createReducer";


const initialState = {
  name: "张三",
  age: 1,
};


const reducer = (state, action) => {
  switch (action.type) {
    case "addAge":
      return {
        ...state,
        age: state.age + 1,
      };
    default:
      return state;
  }
};


export const store = createReducerStore(reducer, initialState);


export default function useTodoStore() {
  /**
   * 返回一个state
   */
  return useSyncExternalStore(store.subscribe, store.getSnapshot);
}
export const { dispatch } = store;

3、页面使用

import { useState, useDeferredValue, useTransition } from "react";

import useTodoStore, { dispatch, store } from "./useReducerStore";

export default function App7() {
  const state = useTodoStore();
  console.log(state)

  const ageAdd = () => {
    dispatch({
      type: "addAge",
    });
  };

  const getStore = () => {
    console.log(store.getSnapshot())  
  }

  return (
    <div className="container">
      <div>哈哈哈</div>
      {state.name} -- {state.age}
      <button onClick={() => ageAdd()}>age + 1</button>
      <button onClick={() => getStore()}>获取store</button>
    </div>
  );
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值