Reactjs - 如何在 reactjs 中加载和映射数据 material table

Reactjs - How to load and map data in reactjs material table

如何在 reactjs 中加载和映射数据 material Table。我通过 Cards 组件将对象传递给子组件。当控制台日志我可以从父级接收对象但它抛出 failed to compile 错误。任何人都可以让我知道我哪里出错了吗?

Card.tsx

function createData(type: any, description: any, volume: any) {
  return { type, description, volume };
}

class Card extends Component {
 constructor(props: any) {
    super(props);
    const rows = props.value.cargo;
    rows.map((data: any) => {
      createData(data.type, data.description, data.volume);
    });
  }

  render() {
    return (
      <Card className="Card">
        <CardContent className="Card-Content">
              <Table className="Card-Content__Table">
                <TableHead>
                  <TableRow>
                    <TableCell>type</TableCell>
                    <TableCell>description</TableCell>
                    <TableCell>volume</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {rows.map(row => (
                    <TableRow key={row.volume}>
                      <TableCell component="th" scope="row">
                        {row.type}
                      </TableCell>
                      <TableCell>{row.description}</TableCell>
                      <TableCell>{row.volume}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
        </CardContent>
      </Card>
    );
  }
}

Cards.tsx

render() {
    return (
      <div>
        {this.state.card.map((card: any) => (
          <Card key={card.id} value={card} />
        ))}
      </div>
    );
  }

您在构造函数中定义的 const rows 无法从 render() 访问。它只能在构造函数中访问。如果你想创建一个可以在整个 class 中访问的参数,你可以这样创建它:

this.rows = props.value.cargo;

然后使用 this.rows 而不是 rows.

访问它

但是,对于这个例子,这没有任何意义,并且将来会给你带来其他问题,因为道具在渲染之间没有正确更新。

您应该在 render() 中使用 this.props.value.cargo.map 而不是 rows.map。如果你想让它更干净,你也可以在 render() 中创建另一个 const rows。它们都具有相同的名称是可以的,因为它们在不同的范围内。