【问题标题】:How to use redux in a vanilla js class?如何在 vanilla js 类中使用 redux?
【发布时间】:2020-09-16 08:37:40
【问题描述】:

我有一个 javascript 类 - 不是 React 组件 - 作为服务来处理 React 应用程序中的逻辑层(api 调用等)。它的方法都使用redux(useSelector或useDispatch),一切正常。

但是,linter 发疯了:

无法在类组件中调用 React Hook "useSelector"。

类如下所示:

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

如何重构这个?

【问题讨论】:

  • 你可以使用react-redux connect,不知道为什么需要一个类,把userService放在一个useRef中。
  • 你会如何将这个服务包装在一个 ref 中?
  • const service = useRef(); useEffect(()=>{service.current = new userService();},[]); 如果您在第一次渲染时需要 userService 实例,则不要第一次渲染:return service.current ? null : <jsx content

标签: javascript reactjs class redux


【解决方案1】:

要访问 redux,这取决于您的上下文:

  • 在 React 函数组件中:使用 react-redux hooks 或 connect
  • 在 React 类组件中:使用 react-redux 连接
  • 在 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"));

【讨论】:

  • 这个解决方案看起来很有希望,但我有以下错误:“类型 '(reducers?: ReducersMapObject>, extendedRootSaga?: Saga) => Store; user: Partial; ... 还有 4 个 ...;" .
  • 错误消息表明您正在调用 reducer 上的调度。您应该改为在 store 实例 上调用 dispatch。您的商店实例是 createStore 返回的对象。
猜你喜欢
  • 2021-05-09
  • 1970-01-01
  • 2017-11-13
  • 2015-02-21
  • 1970-01-01
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多