乐闻世界logo
搜索文章和话题

How to set zustand state in a class component

2 个月前提问
2 个月前修改
浏览次数46

1个答案

1

在使用类组件时,我们无法直接使用zustand的hooks,因为hooks是专为函数式组件设计的。但是,我们可以通过其他方式使类组件访问zustand状态。一种常见的方式是使用高阶组件(HOC)或者使用订阅模式来访问和更新状态。

方案一:使用高阶组件(HOC)

我们可以创建一个高阶组件来包裹我们的类组件,这样就可以在高阶组件内使用zustand的hooks来访问和操作状态,然后将这些状态通过props传递给类组件。

假设我们有一个zustand store,定义如下:

javascript
import create from 'zustand'; const useStore = create(set => ({ count: 0, increment: () => set(state => ({ count: state.count + 1 })), decrement: () => set(state => ({ count: state.count - 1 })) }));

然后我们创建一个高阶组件:

javascript
import React from 'react'; import useStore from './store'; // 引入我们的store const withStore = (Component) => { return function EnhancedComponent(props) { const { count, increment, decrement } = useStore(); return <Component {...props} count={count} increment={increment} decrement={decrement} />; }; }; export default withStore;

现在,我们可以使用这个高阶组件来包裹我们的类组件:

javascript
import React, { Component } from 'react'; import withStore from './withStore'; // 引入高阶组件 class Counter extends Component { render() { const { count, increment, decrement } = this.props; return ( <div> <h1>{count}</h1> <button onClick={increment}>增加</button> <button onClick={decrement}>减少</button> </div> ); } } export default withStore(Counter); // 使用高阶组件包裹类组件

方案二:使用订阅模式

如果你不想使用高阶组件,还可以在类组件内部直接使用zustand的订阅模式。这种方式需要在组件的生命周期中手动处理订阅和取消订阅。

下面是如何在类组件中使用zustand订阅:

javascript
import React, { Component } from 'react'; import useStore from './store'; // 引入store class Counter extends Component { state = { count: useStore.getState().count // 初始状态 }; componentDidMount() { this.unsubscribe = useStore.subscribe(count => { this.setState({ count }); }, state => state.count); } componentWillUnmount() { this.unsubscribe(); } increment = () => { useStore.getState().increment(); }; decrement = () => { useStore.getState().decrement(); }; render() { const { count } = this.state; return ( <div> <h1>{count}</h1> <button onClick={this.increment}>增加</button> <button onClick={this.decrement}>减少</button> </div> ); } } export default Counter;

在这个例子中,我们在组件挂载时订阅了状态变化,并在组件卸载时取消订阅,这样可以确保组件状态始终与zustand store保持同步。

2024年8月1日 09:42 回复

你的答案