在 React 的映射中组合数组和字符串

Combine Array and String in Mapping in React

我需要合并 rowsrows2。如果其中任何一个都没有值,则它们的值为“none”。我如何组合它们?现在的问题是它创建了多个空行。

Codesandbox CLICK HERE

    <TableBody>
      {[...(rows || []), ...(rows2 || [])].map((row) => (
        <TableRow
          key={row.name}
          sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
        >
          <TableCell component="th" scope="row">
            {row.name}
          </TableCell>
          <TableCell align="right">{row.calories}</TableCell>
          <TableCell align="right">{row.fat}</TableCell>
          <TableCell align="right">{row.carbs}</TableCell>
          <TableCell align="right">{row.protein}</TableCell>
        </TableRow>
      ))}
    </TableBody>

您可以使用下面 result 的语法。只需将地图回调函数替换为您想要的任何内容即可:

const rows = [
  {
    name: "frozen yogurt",
    calories: 22,
    fat: 33,
    carbs: 44,
    protein: 44
  },
  // ...
];

const rows2 = "none";

const result = [...(Array.isArray(rows) ? rows : []), ...(Array.isArray(rows2) ? rows2 : [])]
  .map(row => /* whatever you want here, but I'll use */ row);

console.log(result);

或者您可以创建一个函数并重新使用它:

function arrayValueOrEmptyArray (value) {
  return Array.isArray(value) ? value : [];
}

const rows = [
  {
    name: "frozen yogurt",
    calories: 22,
    fat: 33,
    carbs: 44,
    protein: 44
  },
  // ...
];

const rows2 = "none";

const result = [...arrayValueOrEmptyArray(rows), ...arrayValueOrEmptyArray(rows2)].map(row => row);

console.log(result);

问题是您将字符串值“none”散布到字符数组中,然后将其映射到行。这导致对应于 ["n", "o", "n", "e"].

的四个空行

假设您只想组合两个有时可能是字符串的“数组”值,并且只呈现实际具有行数据的行,将 rowsrows2 值复制到数组(不展开),运行 数组通过过滤函数以确保只传递数组类型的值,将数组的数组展平为单个数组,以及然后映射。

{[rows, rows2]
  .filter(Array.isArray)
  .flat()
  .map((row) => (
    <TableRow
      key={row.name}
      sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
    >
      <TableCell component="th" scope="row">
        {row.name}
      </TableCell>
      <TableCell align="right">{row.calories}</TableCell>
      <TableCell align="right">{row.fat}</TableCell>
      <TableCell align="right">{row.carbs}</TableCell>
      <TableCell align="right">{row.protein}</TableCell>
    </TableRow>
  ))}