React-select 如何只渲染未定义的选项值

React-select how to render only option values that are not undefined

我需要根据 if/else 呈现我的 Option 值,这将仅显示与查询

中的参数相关的 option
const renderLsit = useMemo(() => {
    return mediaCategories?.Entities?.map((category, _) => {
      if (
        category.CategoryTypeCode === MediaCategoryType.Other &&
        params.type === "categories"
      ) {
        return {
          value: category.CategoryId,
          label: category.CategoryName,
          index: category.CategoryId,
        };
      } else if (
        category.CategoryTypeCode === MediaCategoryType.Main &&
        params.type === "genre"
      ) {
        return {
          value: category.CategoryId,
          label: category.CategoryName,
          index: category.CategoryId,
        };
      }
    });
  }, [params, mediaCategories.Entities]);

但是 renderList 在映射后包含 undefined 个值,这是制动反应-select。所以它返回这样的东西: 这是 else if 而我的 Entities 列表没有 undefined

可以在 .map()

之前做一个 .filter()
return mediaCategories?.Entities?.filter(c => c !== undefined /*or whatever you want filter on*/).map((category, _) => {
      if (
        category.CategoryTypeCode === MediaCategoryType.Other &&
        params.type === "categories"
      ) {
        return {
          value: category.CategoryId,
          label: category.CategoryName,
          index: category.CategoryId,
        };
      } else if (
        category.CategoryTypeCode === MediaCategoryType.Main &&
        params.type === "genre"
      ) {
        return {
          value: category.CategoryId,
          label: category.CategoryName,
          index: category.CategoryId,
        };
      }
    });

在映射之前添加过滤器以过滤掉空值

 mediaCategories?.Entities?.filter(Boolean).map((category, _) =>

以更惯用/ES6 的方式:

const renderList = useMemo(() => {
    return mediaCategories?.Entities?.filter(
        ({ CategoryTypeCode }) =>
            (CategoryTypeCode === MediaCategoryType.Other &&
                params.type === "categories") ||
            (CategoryTypeCode === MediaCategoryType.Main &&
                params.type === "genre")
    ).map((category) => ({
        value: category.CategoryId,
        label: category.CategoryName,
        index: category.CategoryId,
    }));
}, [params, mediaCategories.Entities]);