在 HOC 部分的 React 文档中,有一个示例
const CommentListWithSubscription = withSubscription(
CommentList,
(DataSource) => DataSource.getComments()
);
你能解释一下函数作用域是如何工作的吗? 他们将第二个参数作为箭头函数,在这个箭头函数中,我们DataSource
参数并返回DataSource.getComments()
通过订阅实现 HOC
function withSubscription(WrappedComponent, selectData) {
return class extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
data: selectData(DataSource, props)
};
}
...
在这里,他们使用selectData
作为该函数(DataSource) => DataSource.getComments()
并使用DataSource
参数再次触发该功能
这一刻有点困惑,是我们放在上面箭头函数中的相同DataSource
还是不同? 一般来说它是如何工作的?
HOC (withSubscription
( 中的DataSource
是该作用域或全局作用域中的现有变量,可能通过静态导入或上下文获得。
父项(调用 HOC 的代码(中的DataSource
只是一个位置保存参数。基本上,父级告诉HOC:"我不知道您正在使用什么数据源,只需从中检索注释(DataSource.getComments()
(并将其用作状态数据"。
如果父实例希望另一个 HOC 实例使用不同的数据(如示例中的博客文章(,它只需更改该 HOC 的指令以DataSource.getBlogPost()
,可能使用通过 HOCprops
传递的一些额外参数,如示例中所示。这种模式使 HOC 尽可能灵活。
HOC 概念
任何hoc都是一个普通的函数,它返回一个反应组件,但修改了props
考虑 React 文档中的示例:
const CommentListWithSubscription = withSubscription(
CommentList,
(DataSource) => DataSource.getComments()
);
我同意这绝对不是一个最简单的例子。
考虑一个简单的 HOCwithData
const withData = (component, endpoint) => {
function WrappedComponent(props) {
const [data, setData] = useState(null);
useEffect(() => {
fetch(endpoint).then((res) => setData(res));
}, []);
return (
<component data={data} {...props} />
);
}
return WrappedComponent;
};
const ComponentWithData = withData(MyCustomComponent, api_endpoint)
function MyCustomComponent (props){
const { data } = props
// use this data to do whatever
}
当一个道具被注入像data={[1,2,3]}
这样的<component/>
时,该道具可以通过生成的组件的道具来访问,如props.data
withSubscription 需要 2 个参数:WrappedComponent 和 selectData。 请注意,在 withSubscription 的构造函数中,他们将初始状态设置为等于调用 selectData 的结果。selectData 使用 2 个参数调用:数据源是第一个参数,props 是第二个参数。 在这种情况下,数据源可能是他们之前导入的某个模块,但只是没有向您展示......
当他们用"withSubscription"包装CommentListWithSubscription时,数据源就是在构造函数中传递以初始化状态的数据源。他们应该将其命名为数据源,这是正确的命名约定。
希望对:)有所帮助 如果从他们的文档中不了解 HOC,请继续搜索其他来源。有成百上千个来源可以解释这个概念。在编程中,您有时需要通过多个来源才能正确理解一个概念或想法。祝你好运!