8

我正在一个站点上工作,该站点使用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>
    );
  }
}
4

5 回答 5

5

类组件最接近钩子的是高阶组件 (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);
于 2021-02-07T07:30:42.123 回答
1

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

store.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>
  );
};

index.js

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

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

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

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>
  );
}

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;

换入新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>
  );
}

编辑 how-to-set-zustand-state-in-a-class-component

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

<ZustandContext.Consumer>
  {({ setPink }) => <MyClass setPink={setPink} />}
</ZustandContext.Consumer>

我的课

<button onClick={this.props.setPink}>Set State Class</button>
于 2021-02-07T06:30:43.477 回答
1

似乎它使用了钩子,因此在课堂上您可以使用该实例:

import { useStore } from "./store";

class MyClass extends Component {
  render() {
    return (
      <div>
        <button
          onClick={() => {
            useStore.setState({ isPink: true });
          }}
        >
          Set State Class
        </button>
      </div>
    );
  }
}

编辑 gracious-frost-9vdu3

于 2021-02-07T06:30:44.037 回答
0

我喜欢创建一个类似于 redux connect 的高阶组件:

function connectZustand(useStore, selector) {
    return (Component) =>
        React.forwardRef((props, ref) => <Component ref={ref} {...props} {...useStore(selector, shallow)} />);
}

例如:

import React, { Component } from 'react';
import create from 'zustand';
import shallow from 'zustand/shallow';

function connectZustand(useStore, selector) {
    return (Component) =>
        React.forwardRef((props, ref) => <Component ref={ref} {...props} {...useStore(selector, shallow)} />);
}

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

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

const MyClassWithZustand = connectZustand(useStore, (state) => ({ setPink: state.setPink }))(MyClass);

export default function Test() {
    const isPink = useStore((state) => state.isPink);
    return (
        <>
            <MyClassWithZustand />
            {isPink ? 'Is Pink' : 'Is Not Pink'}
        </>
    );
}
于 2021-09-29T19:51:00.333 回答
0

这对我来说效果很好。:

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

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

  render() {
    return (
      <div>
        <button
          onClick={
              useStore.getState().setPink() // <-- Changed code
          }
        >
          Set State Class
        </button>
      </div>
    );
  }
}

export default MyClass;
于 2021-04-21T05:02:08.187 回答