javascript - 在 React 中记忆一个函数
问题描述
有一个组件接收道具。
props 有一个数组的形状,对于这个数组的每个元素,一个函数将返回一个不同的组件来渲染。
function MainComponent ({ data }) => { // data is props, an array
const specialFunction = (index) => {
switch (index) {
case 0:
return <Component0 />;
case 1:
return <Component1 />;
case 2:
return <Component2 />;
default:
return null;
}
};
...
return (
...
data.map((item, index) => {
... // do other stuff with item
<div>{specialFunction(index)}</div> // the function that we talk about
...
);
如果道具不会改变,有没有办法记住这个结果?或者有什么更好的写法?
解决方案
带有空依赖数组的useCallback将是这里的最佳方法。useCallback 将返回回调的记忆版本,仅当其中一个依赖项发生更改时才会更改。由于我们的依赖数组是[]
,它只会被初始化一次,并且返回的 memonized 函数将在后续函数调用中使用。
const specialFunction = useCallback((index) => {
switch (index) {
case 0:
return <Component0 />;
case 1:
return <Component1 />;
case 2:
return <Component2 />;
default:
return null;
}
}, []);
推荐阅读
- firebase - 将用户参数“值”链接到 Firebase 事件控制台中的事件值
- nginx - 基于响应的 Nginx 上游重试
- c# - 在 IIS 服务器上托管网站时无法创建数据库。在本地它正在工作
- python - 如何在 Openpyxl 中获取当前活动工作表的名称
- apache-spark - 当我尝试从检查点重新启动作业时,触发广播变量的类型应该是数字还是字符串
- android - 在构建的 APK 的根目录中包含一个文件
- tensorflow - Tensorflow 1.11 需要 CUDA 9.0 的 CuDNN 7.2,但是没有这样的库
- php - How to get the feedback of DB insert laravel
- rest - 用于重载 GET 动词的 REST 策略
- python - CSV 结果覆盖值