使用传递 props.children 作为 React 元素的 redux connect 函数

Use redux connect function passing props.children as React element

我需要一个组件,它在安装后立即从 API 开始轮询数据,并在卸载时停止。数据必须可用于子组件。

这是我当前的实现框架

class External extends Component {
  render() {
    const ConnectedPoller = connect(/*cut*/)(Poller)

    return <ConnectedPoller {...this.props}>
      {this.props.children}
    </ConnectedPoller>
  }
}

class Poller extends Component {
  componentDidMount() {
    this.model.startPolling();
  }

  componentWillUnmount() {
    this.model.stopPolling();
  }

  render() {
    const children = React.Children.map(this.props.children, child => {
      return React.cloneElement(child, {...this.props});
    });

    return children;
  }
}

有一些组件需要这些数据,我可以通过这种方式将我的轮询器用作它们的父组件

<External>
  <ComponentRequiringData {...this.props}>
</External>

这是可行的,但我想将 External 合并到 Poller 中。问题是我找不到办法做到这一点

const ConnectedPoller = connect(/*cut*/)(this.props.children)

当我传递 props.children 而不是 "real" 反应元素时,connect 函数会报错。有什么建议吗?

免责声明:我不在祖先级别进行轮询,因为这对后端来说是一项耗费大量资源的任务,而且我只需要少数几个组件中的数据,这些组件很少使用并且永远不会在同一页面中一起呈现.

使用 redux 的连接函数的唯一原因是,如果你想连接到状态管理——要么获取当前状态,要么调度一个动作。由于您在这里没有执行任何这些操作,因此没有理由使用 connect。此外,虽然它可能有效,但没有理由在渲染函数中使用 connect 。这将无缘无故地一遍又一遍地重新创建组件。我猜你这样做是因为你想传递带有 props 的组件,但是 connect 可以从父元素接收 props 作为第二个参数。