首页 > 解决方案 > 如何在类组件中设置 zustand 状态

问题描述

我正在一个站点上工作,该站点使用zustand将全局状态存储在一个文件中。我需要能够在类组件中设置该状态。我可以使用钩子在功能组件中设置状态,但我想知道是否有办法将 zustand 与类组件一起使用。

如果有帮助,我已经为此问题创建了一个沙箱: https ://codesandbox.io/s/crazy-darkness-0ttzd

在这里,我在功能组件中设置状态:

function MyFunction() {
  const { setPink } = useStore();

  return (
    <div>
      <button onClick={setPink}>Set State Function</button>
    </div>
  );
}

我的状态存储在这里:

export const useStore = create((set) => ({
  isPink: false,
  setPink: () => set((state) => ({ isPink: !state.isPink }))
}));

如何在类组件中设置状态?:

class MyClass extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    return (
      <div>
        <button
          onClick={
            {
              /* setPink */
            }
          }
        >
          Set State Class
        </button>
      </div>
    );
  }
}

标签: reactjsreact-hooksstatereact-state-managementzustand

解决方案


类组件最接近钩子的是高阶组件 (HOC) 模式。让我们把钩子翻译useStore成 HOC withStore

const withStore = BaseComponent => props => {
  const store = useStore();
  return <BaseComponent {...props} store={store} />;
};

我们可以在任何用withStore.

class BaseMyClass extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    const { setPink } = this.props.store;
    return (
      <div>
        <button onClick={setPink}>
          Set State Class
        </button>
      </div>
    );
  }
}

const MyClass = withStore(BaseMyClass);

推荐阅读