Zustand:源自同一州其他房产的房产

Yui*_*Yui 2 state-management reactjs react-state-management zustand

考虑以下 zustand 商店:

const useStore = ((set) => ({
   property1: 2,
   property2: 3,
   property3: 6,
   //etc.
}))
Run Code Online (Sandbox Code Playgroud)

其中属性 3 是属性 1 和属性 2 的倍数。是否可以将其设置为当 zustand 中的 property1 或 property2 更新时 property3 自动更新?

小智 5

选项 1:您可以在 React 组件内使用钩子,该钩子将拥有自己的状态,并在 property1 或 property2 更新时更新。

function Component() {
    const property1 = useStore(state => state.property1);
    const property2 = useStore(state => state.property2);

    // Just for example, this multiples property 1 by property 2
    const property3 = property1 * property2;
}
Run Code Online (Sandbox Code Playgroud)

选项 2:您可以使用zustand-store-addons,它添加计算属性

import create from 'zustand-store-addons';

const useStore = create(
    (set) => ({
        property1: 2,
        property2: 3
    }),
    // Second object is for the addons
    {
        computed: {
            // Recomputes every time property1 or property2 changes.
            property3() {
                return this.property1 * property2;
            }
        }
    }
};

// The useStore state will look like
{
    property1: 2,
    property2: 3,
    property3: 6
}
Run Code Online (Sandbox Code Playgroud)

如果您仅在一个组件中使用该属性,则选项 1 会更好,但如果您希望它成为全局属性,则选项 2 会更好。

  • 还有这些中间件库: https://github.com/chrisvander/zustand-compulated https://github.com/cmlarsen/zustand-middleware-compulated-state (2认同)