【问题标题】:React HOC with 'recompose' and 'redux-cycles'. How to make it work?用 'recompose' 和 'redux-cycles' 反应 HOC。如何让它发挥作用?
【发布时间】:2026-01-09 10:25:01
【问题描述】:

所以,我一直在玩 recompose,然后,我发现了这个 redux-cycles,我认为它非常适合我的目标:函数式 JS 和反应性。

问题是当我使用 HoC(Recompose) 创建组件时,我无法让事件监听器工作。 Ps:当我创建常规 React 组件时,事件监听器起作用

在重构 API 中,有一些 Observable Utilities,我认为这是我的代码失败的地方。我想我需要它来使 redux-cycles 与 recompose 一起工作,但我无法让它工作。

使用常规 React 组件和“redux-cycles”的工作示例:JS Bin

因为它适用于常规的 React 组件和常规的 redux 存储(没有“redux-cycles”),所以我只发布 HoC 代码:

/* eslint no-console: ["error", { allow: ["warn", "error"] }] */

import React from 'react';
import {
  compose,
  onlyUpdateForPropTypes,
  pure,
  setObservableConfig,
  setPropTypes,
  withReducer,
  withPropsOnChange,
} from 'recompose';
import xstreamConfig from 'recompose/xstreamObservableConfig';

import counterReducer from '../reducer';

setObservableConfig(xstreamConfig);

const enhance = compose(
  pure,
  onlyUpdateForPropTypes,
  setPropTypes({
    counter: React.PropTypes.number,
    increment: React.PropTypes.func,
    decrement: React.PropTypes.func,
  }),
  withPropsOnChange(['counter'], ({ counter }) => ({ counter })),
  withReducer('counter', 'dispatch', counterReducer, 0),
);

const Counter = enhance(({ counter, dispatch }) => (
  <div>
    <h1>Counter module</h1>
    <p>{counter}</p>
    <button onClick={() => dispatch({ type: 'INCREMENT_ASYNC' })}> + </button>
    <button onClick={() => dispatch({ type: 'DECREMENT_ASYNC' })}> - </button>
  </div>
));

export default Counter;

【问题讨论】:

    标签: javascript reactjs redux recompose


    【解决方案1】:

    recompose/withReducer 没有连接到你的 Redux 存储。相反,它会在您的 HOC 中创建一个本地存储,其工作方式类似于 redux。所以如果你想从 Redux store 消费,你应该使用react-redux/connect

    【讨论】:

    • 它确实与商店连接。没有 Redux-cycles 它可以正常工作。
    • 哦,我明白你在说什么。我的错。会试试的。
    • @KadoBOT 一切顺利吗?
    • 是的,它确实可以与“连接”一起使用,但我仍然不相信使用“重构”中的可观察实用程序之一不会出现转机。
    • 您可以在connect() 之后使用recompose 的Observable 实用程序,例如:compose(connect(), mapPropsStream())
    最近更新 更多