Commit 73863a6f authored by Chunchi Che's avatar Chunchi Che

Merge branch 'feat/observeStore' into 'main'

Feat/observe store

See merge request mycard/Neos!24
parents 83c0f275 5a4ce916
Pipeline #18170 passed with stages
in 3 minutes and 19 seconds
/*
* 全局状态存储模块
* */
import { configureStore } from "@reduxjs/toolkit";
import { configureStore, Unsubscribe } from "@reduxjs/toolkit";
import joinedReducer from "./reducers/joinSlice";
import chatReducer from "./reducers/chatSlice";
import playerReducer from "./reducers/playerSlice";
......@@ -18,5 +18,25 @@ export const store = configureStore({
},
});
// Ref: https://github.com/reduxjs/redux/issues/303
export function observeStore<T>(
select: (state: RootState) => T,
onChange: (prev: T | null, cur: T) => void
): Unsubscribe {
let currentState: T | null = null;
const changeHook = () => {
const nextState = select(store.getState());
if (nextState !== currentState) {
onChange(currentState, nextState);
currentState = nextState;
}
};
const unsubscribe = store.subscribe(changeHook);
changeHook();
return unsubscribe;
}
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
......@@ -6,7 +6,7 @@
import { IDuelPlate, TypeSelector } from "../duel";
import { useAppSelector } from "../../../hook";
import React, { useEffect, useRef } from "react";
import type { RootState } from "../../../store";
import { RootState, observeStore } from "../../../store";
import * as BABYLON from "@babylonjs/core";
import renderHands from "./hands";
import renderMonsters from "./monsters";
......@@ -107,6 +107,26 @@ export default class SimpleDuelPlateImpl implements IDuelPlate {
});
}, [canvasRef, hands]);
useEffect(() => {
// 监听状态变化,并实现动画
const onHandsChange = (
prev_hands: CardMeta[] | null,
cur_hands: CardMeta[]
) => {
console.log(prev_hands, "change to", cur_hands);
};
const unsubscribe = observeStore(
this.handsSelector || defaultHandsSelector,
onHandsChange
);
return () => {
// 取消监听
unsubscribe();
};
}, []);
return (
<canvas
width={window.innerWidth}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment