gpt4 book ai didi

javascript - React - Render 中的 HOCs - 规则有异常(exception)吗?

转载 作者:行者123 更新时间:2023-12-03 06:59:39 25 4
gpt4 key购买 nike

我通过使用多种组件组合技术实现了 Pub/Sub 模式:React.cloneElement 和功能性“组合组件”。我们的目标是能够通过为组件分配一个“主题”属性来动态地将组件注册到不同的数据流中。
例如,此组件接收发布到 HELLO_WORLD 主题的所有数据:

 <MyComponent topic="HELLO_WORLD" />
下面是 MyComponent 的内部表示为一个函数式组件:
export const MyComponent = props => subscribe(({ topic, data }) => {
return <span>I am listening to the {topic} topic. Current state: {data}</span>
}, props.topic);
或者,这里它被表示为一个类组件:
class MyComponent extends React.Component {
render() {
const { props: { otherProps, topic } } = this;
return subscribe(({ data }) => {
return <span>I am listening to the {topic} topic. Current state: {data}</span>
}, topic)
}
}
如您所见,此模式需要在渲染函数内返回一个高阶组件。您认为这是否属于上述警告here ?
这里有一些更多的背景:
subscribe 函数返回一个组合组件:
const subscribe = (Comp, topic) => {
return (
<Subscriber topic={topic}>
<Comp />
</Subscriber>
);
};
它将 MyComponent 包装在订阅者中:
class Subscriber extends Component {
state = publisher.getState(this.props.topic) // get initial state

onMessage = msg => {
this.setState({ ...msg });
return this.state;
}

componentDidMount() {
this.subscription = publisher
.subscribe(this.props.topic, this.onMessage);
}

componentWillUnmount() {
publisher.unsubscribe(this.props.topic, this.onMessage);
}

render() {
const {
state: { data },
props: { children }
} = this;
return Children.map(children, child =>
cloneElement(child, { ...this.props, data })
);
}
}
订阅者从发布者那里获取它的状态,发布者缓存主题:
const eventEmitter = new EventEmitter();

const publisher = {
subscribe: function (eventName, cache) {
eventEmitter.on(eventName, data => {
this.cache[eventName] = cache(data);
});
},
unsubscribe: function (eventName, fn) {
eventEmitter.off(eventName, fn)
},
send: function (eventName, payload) {
eventEmitter.emit(eventName, payload);
if (!this.cache[eventName]) {
this.cache[eventName] = { data: payload };
}
},
getState: function (topic) {
return this.cache[topic] || {};
},
cache: {}
}
组件分析器表明此设置渲染非常高效。此外,状态保存在 React 区域之外的缓存中。如果你问我,它几乎只是带有扭曲的 Flux。你的意见?

最佳答案

您的 subscribe()不是真正的 HOC。
为什么 ? (专注于粗体字)

  • HOC 是纯粹的 功能 返回一个容器组件
    包裹原始组件。
  • subscribe()只是包装组件 这只是包装
    原始组件并返回。

  • 这是一个详细的答案:
    https://stackoverflow.com/a/64178585/8323442

    关于javascript - React - Render 中的 HOCs - 规则有异常(exception)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64346058/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com