如何在类组件中设置 zustand 状态

who*_*oMe 7 state reactjs react-state-management react-hooks 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>
  );
}
Run Code Online (Sandbox Code Playgroud)

我的状态存储在这里:

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

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

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

  render() {
    return (
      <div>
        <button
          onClick={
            {
              /* setPink */
            }
          }
        >
          Set State Class
        </button>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Jem*_*alo 16

类组件与钩子最相似的是高阶组件 (HOC) 模式。让我们将钩子翻译useStore成 HOC withStore

const withStore = BaseComponent => props => {
  const store = useStore();
  return <BaseComponent {...props} store={store} />;
};
Run Code Online (Sandbox Code Playgroud)

我们可以将存储作为包装在任何类组件中的 prop 进行访问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);
Run Code Online (Sandbox Code Playgroud)


Dre*_*ese 3

创建一个功能组件和基于类的组件都可以使用的 React Context 提供程序。将useStore钩子/状态移动到上下文提供者。

商店.js

import { createContext } from "react";
import create from "zustand";

export const ZustandContext = createContext({
  isPink: false,
  setPink: () => {}
});

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

export const ZustandProvider = ({ children }) => {
  const { isPink, setPink } = useStore();

  return (
    <ZustandContext.Provider
      value={{
        isPink,
        setPink
      }}
    >
      {children}
    </ZustandContext.Provider>
  );
};
Run Code Online (Sandbox Code Playgroud)

索引.js

用该ZustandProvider组件包装您的应用程序。

...
import { ZustandProvider } from "./store";
import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <ZustandProvider>
      <App />
    </ZustandProvider>
  </StrictMode>,
  rootElement
);
Run Code Online (Sandbox Code Playgroud)

使用ZustandContext两个组件中的上下文

MyFunction.js

import React, { useContext } from "react";
import { ZustandContext } from './store';

function MyFunction() {
  const { setPink } = useContext(ZustandContext);

  return (
    <div>
      <button onClick={setPink}>Set State Function</button>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

MyClass.js

import React, { Component } from "react";
import { ZustandContext } from './store';

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

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

MyClass.contextType = ZustandContext;
Run Code Online (Sandbox Code Playgroud)

换入新ZustandContextApp而不是useStore直接使用钩子。

import { useContext} from 'react';
import "./styles.css";
import MyClass from "./MyClass";
import MyFunction from "./MyFunction";
import { ZustandContext } from './store';

export default function App() {
  const { isPink } = useContext(ZustandContext);

  return (
    <div
      className="App"
      style={{
        backgroundColor: isPink ? "pink" : "teal"
      }}
    >
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <MyClass />
      <MyFunction />
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

编辑如何在类组件中设置 zustand-state

如果您无法在MyClass组件上设置任何特定上下文,您可以使用ZustandContext.Consumer来提供setPink回调作为 prop。

<ZustandContext.Consumer>
  {({ setPink }) => <MyClass setPink={setPink} />}
</ZustandContext.Consumer>
Run Code Online (Sandbox Code Playgroud)

我的课

<button onClick={this.props.setPink}>Set State Class</button>
Run Code Online (Sandbox Code Playgroud)