reactjs - 如何在类组件中设置 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>
);
}
}
解决方案
类组件最接近钩子的是高阶组件 (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);
推荐阅读
- c++ - 没有轮询的 SDL2 事件回调
- android - CollapsingToolbarLayout 包含 ViewPager 和一个搜索框。如何防止搜索框仅折叠,而 ViewPager 折叠
- scala - scala 和 dotty 的下限和上限类型
- javascript - JavaScript:打印动态值/数据
- google-cloud-platform - GCP:创建包括运行时进程的 VM 快照
- java - 在用户的 gmail 中更新时,无法更新 firebase 数据库中的数据
- python-3.x - psycopg2 不会将数据保存到 postgres 数据库中
- javascript - 无法使用 JQuery 获取输入字段的值
- amazon-web-services - AWS 为 S3 文件夹级别访问生成动态凭证?
- javascript - d3js连续节点颜色网络 - 无法找出问题