中间件
immer
import create from "zustand";
import { immer } from "zustand/middleware/immer";
const useStore = create(
immer((set) => ({
bees: 0,
addBees: (by) =>
set((state) => {
state.bees += by;
}),
}))
);
redux
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import create from "zustand";
import { devtools, redux } from "zustand/middleware";
import "./styles.css";
const initialState = { count: 0 };
const types = { increase: "INCREASE", decrease: "DECREASE" };
const reducer = (state, { type, by }) => {
switch (type) {
case types.increase:
return { count: state.count + by };
case types.decrease:
return { count: state.count - by };
default:
return;
}
};
const useStore = create(
// Connects store to devtools
// Without reducers and action-types you would see "setState" logged out instead
devtools(
// Transforms our store into a redux action dispatcher ...
// Adds a dispatch method to the store as well as to the api
redux(reducer, initialState)
)
);
function Counter() {
const { count, dispatch } = useStore((state) => ({
count: state.count,
dispatch: state.dispatch,
}));
useEffect(() => {
// Increase
setTimeout(() => dispatch({ type: types.increase, by: 3 }), 1000);
// Decrease
setTimeout(() => dispatch({ type: types.decrease, by: 1 }), 2000);
// Decrease
setTimeout(() => dispatch({ type: types.decrease, by: 1 }), 3000);
}, []);
return <span class="header">{count}</span>;
}
ReactDOM.render(<Counter />, document.getElementById("root"));
Redux Devtools
interface BearState {
bears: number;
increase: (by: number) => void;
}
const useStore = create<BearState>()(
devtools(
set => ({
bears: 0,
increase: by => set(state => ({ bears: state.bears + by }), false, 'bearIncrease'),
}),
{ name: 'testStore' }
)
);
内置中间件列表 https://github.com/pmndrs/zustand/tree/main/src/middleware
第三方中间件 https://github.com/pmndrs/zustand/wiki/3rd-Party-Libraries
扩展
精读《zustand 源码》 https://zhuanlan.zhihu.com/p/461152248
还在学 Redux?不妨提前学下它以后的替代品!——Zustand 源码解析 https://zhuanlan.zhihu.com/p/353135461