reactjs - React - “不要在组件的渲染方法中使用 HOC”是什么意思。访问组件定义之外的 HOC。'?
问题描述
我正在学习 HOC 并继续阅读上面的引用,但我不明白它的含义。如果我的 HOC 向我的消费组件添加了一个方法,我可以像这样在渲染方法中使用该方法吗?如果不是,我将如何做我在这里尝试做的事情:
import React, { Component } from 'react';
import { withMyHOC } from '../with_my_component'
class MyComponent extends Component {
constructor(props) {
super(props);
}
render() {
const { methodFromHOC }= this.props;
const result = methodFromHOC(someArgument);
return (
<div >
{result}
</div>
)
}
}
export default withMyHOC(MyComponent );
解决方案
当你说不要在 render 方法中使用 HOC 时,这意味着你不应该在另一个组件的 render 方法中创建被 HOC 包装的组件的实例。例如,如果你有一个使用 MyComponent 的 App 组件,它不应该像下面这样
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
}
render() {
const { methodFromHOC }= this.props;
const result = methodFromHOC(someArgument);
return (
<div >
{result}
</div>
)
}
}
export default MyComponent;
import { withMyHOC } from '../with_my_component'
export default class App extends React.Component {
render() {
const Wrap = withMyHOC(MyComponent);
return (
<div>
{/* Other Code */}
<Wrap />
</div>
)
}
}
为什么你不应该像上面那样使用它是因为每次调用渲染方法时MyComponent
都会创建一个由 HOC 包装的新实例,Wrap
因此每次它都会被再次挂载而不是通过自然生命周期或 React。
但是,如果您的 HOC 将函数作为道具传递,您可以在渲染中使用它,只要它不会再次导致重新渲染,否则将导致无限循环。
此外,最好记住直接在渲染中调用的函数,以避免一次又一次的计算
推荐阅读
- javascript - 如果json对象键在javascript中具有所有相同的值,如何检查并返回true?
- elasticsearch - 在elasticsearch中查找带小数点零的数字
- android - “com.android.asset-pack”-on-demand 会影响 InstallApp 吗?
- javascript - Javascript延迟更改布尔值
- node.js - 尝试通过 Typeorm 将值插入 Mssql 数据库时出现“ERR_INVALID_ARG_TYPE”错误
- ksh - 如何在变量 $File Equals 中使用的文件名中包含变量
- sql - 添加 order by 时查询退化为 PK 扫描
- .net-core - 在 .net core 3.1 中生成模式
- c# - 如何将 SharePoint 2013 列表中的数据导出到可以打印为 PDF 的空白页中
- web-config - 我应该如何编写 web.config 规则以免它们发生冲突?