[英]Use redux connect function passing props.children as React element
I need a component that starts polling for data from an API as soon as it gets mounted and it stops when unmounted. 我需要一个组件,该组件在挂载后立即开始从API轮询数据,而在卸载时停止。 The data must be available for a child component.
该数据必须可用于子组件。
This is my current implementation skeleton 这是我当前的实现框架
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;
}
}
There are a few components that need these data, I can use my poller as their parent in this way 有一些组件需要这些数据,我可以通过这种方式将轮询器用作其父级
<External>
<ComponentRequiringData {...this.props}>
</External>
This is working, but I would like to merge External
into Poller
. 这是可行的,但我想将
External
合并到Poller
。 The problem is that I cannot find a way to do this 问题是我找不到办法
const ConnectedPoller = connect(/*cut*/)(this.props.children)
The connect
function complains when I pass props.children
instead of a "real" react element. 当我传递
props.children
而不是“真正的” react元素时, connect
函数会抱怨。 Any suggestion? 有什么建议吗?
DISCLAIMER: I don't poll at an ancestor level because it's a heavy resource-consuming task for the backend and I need those data only in a few components that are used rarely and are never rendered together in the same page. 免责声明:我不会在祖先级别进行轮询,因为这对于后端来说是一项繁重的资源消耗任务,而我只需要那些很少使用且永远不会在同一页面中一起呈现的组件中的数据。
The only reason to use redux' connect function, is if you want to connect to the state manangement - either get a the current state, or dispatch a function. 使用redux的connect函数的唯一原因是,如果您想连接到状态管理-获取当前状态或调度一个函数。 Since you aren't doing any of these here, there is no reason to use
connect
. 由于您在这里没有执行任何操作,因此没有必要使用
connect
。 Also, while it might work, there is no reason to use connect inside a rendering function. 同样,尽管可能可行,但没有理由在渲染函数中使用connect。 This will recreate the commponent over and over again for no reason.
这将无缘无故地一次又一次地创建组件。 I guess you are doing it because you want to pass the component with props, but connect can receive props from a parent element as a second argument.
我猜您正在这样做是因为您想通过props传递组件,但是connect可以从父元素接收props作为第二个参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.