在本机反应中获取数组映射中的非空项目

Get non empty items in array map in react native

我已经反应本机循环来填充 select 如下所示的项目

   const categorylist = arr.map((data, key) => {
      if (data != "") {
        return <Select.Item label={data} value={data} key={data} />;
      }
    });

我像下面一样循环使用它,当数组包含非空值时它工作正常,但是当有空值时我得到错误

TypeError: null 不是对象(正在计算 'child.props')

   <Select>
     {categorylist2}
    </Select>

如何使用 map 仅发送非空数组项。请注意我不希望 arr 受到影响,因为我需要它在其他功能中保持不变。

只有数组不为空时才需要遍历数组,使用filter(Boolean)过滤掉空的

const newArr = arr.filter(Boolean);
const categorylist = (newArr.length > 0) && newArr.map((data, key) => {
    return <Select.Item label={data} value={data} key={data} />;
});

这是因为在您的地图中您没有 return 任何空值,这意味着空值,这就是您出现错误的原因。映射函数应该总是 return something.

像这样在映射之前使用过滤器:

arr.filter(data => data !== "").map(data => )

可以通过reducer函数实现

Using Array.filter() then Array.map() traverses the array twice, but you can achieve the same effect while traversing only once with Array.reduce(), thereby being more efficient.

更多信息here

const categorylist = arr.reduce((prev, current, index) => {
      if (current != "") {
        prev.push(<Select.Item label={current} value={current} key={current} />);
      }
      return prev;
    }, []);
    
    console.log(categorylist);

filter 出空元素然后 map 遍历数组 filter returns.

这是一个人为的示例,向您展示它是如何工作的。

const arr = [undefined, 'Bob', '', 'Sally', 'Joe', '', null, 'Pam'];

// `filter` out the empty/null/undefined elements
// and then `map` over that filtered array
const out = arr
  .filter(el => el)
  .map(el => `<div>${el}</div>`);

document.body.innerHTML = out.join('');