简体   繁体   English

如何在 vanilla js 类中使用 redux?

[英]How to use redux in a vanilla js class?

I have a javascript class - not a React component - that acts as a service to handle logic tier (api call, etc.) in a React application.我有一个 javascript 类 - 不是 React 组件 - 它充当服务来处理 React 应用程序中的逻辑层(api 调用等)。 Its methods all use redux (useSelector or useDispatch), and everything works fine.它的方法都使用 redux(useSelector 或 useDispatch),一切正常。

However, the linter goes mad:然而,短绒发疯了:

React Hook "useSelector" cannot be called in a class component. React Hook "useSelector" 不能在类组件中调用。

The class looks like this:这个类看起来像这样:

 export class UserService implements ProjectService { private userService: UserService; constructor(dependencies: Dependencies) { this.userService = dependencies.userService; } public updateUserProfile(id: string) { const dispatch = useDispatch(); return (user: User) => { return dispatch(Event.userManager(user)); }; } }

How to refactor this?如何重构这个?

To access redux, it depends on your context:要访问 redux,这取决于您的上下文:

  • in React function component: use react-redux hooks or connect在 React 函数组件中:使用 react-redux hooks 或 connect
  • in React class component: use react-redux connect在 React 类组件中:使用 react-redux connect
  • outside a React class: use redux Store API :在 React 类之外:使用redux Store API
import { store } from "where you create and export your store";
store.dispatch({type: ... });
const events = store.getState().events;
store.subscribe(() => console.log("The store has been modified"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM