【问题标题】:useMemo on function used in .map statementuseMemo on .map 语句中使用的函数
【发布时间】:2020-03-18 14:13:31
【问题描述】:

我对钩子非常陌生,所以在这里有一个问题: 我有像

这样的 React 组件功能
const getSection = assignmentSectionId => {
    const findSection = sections.find(
      section => section.sectionRefId === assignmentSectionId,
    );

    return findSection ? findSection.name : '';
  };

现在我得到了在该函数上使用 useMemo 的建议。目前我正在使用:

return (
    <List
      role="list"
      aria-label={ariaLabel}
    >
      {assignments.map(assignment => {
        const sectionName = getSection(assignment.sectionId);

        return (
          <Card
            name={sectionName}
          />
        );
      })}
    </List>
  );
};

如果可能的话,在这里使用 useMemo 的最佳(最佳)方式是什么?

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    您可以在useMemo 中使用Array#map。它只会在assignments 值更改后重新渲染列表

    const memoList = React.useMemo(()=> assignments.map(assignment => {
            const sectionName = getSection(assignment.sectionId);
            return (<Card  name={sectionName}/>)
          }),[assignments])
    
    return (
        <List role="list" aria-label={ariaLabel}>{memoList}</List>
      );
    };
    

    【讨论】:

      【解决方案2】:

      这样解决:

      const assignmentData = useMemo(() =>
          assignments.map(
            assignment => {
              const matchedSection = sections.find(
                section => section.sectionRefId === assignment.sectionId,
              );
              return {
                sectionName: matchedSection ? matchedSection.name : '',
              };
            },
            [assignments, sections],
          ),
        );
      
      
      return (
          <List
            role="list"
            aria-label={ariaLabel}
          >
            {assignmentData.map(assignment => {
              return (
                <Card
                  name={assignment.sectionName}
                />
              );
            })}
          </List>
        );
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多