0

如何在 reactjs 材料中加载和映射数据。我正在通过组件将对象传递给子Cards组件。当控制台日志时,我可以从父级接收对象,但它会抛出failed to compile错误。谁能让我知道我在哪里犯了错误?

卡片.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>
    );
  }
}

卡片.tsx

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

1 回答 1

1

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

this.rows = props.value.cargo;

然后使用this.rows而不是仅访问它rows

但是,对于此示例,这没有任何作用,并且将来会给您带来其他问题,因为道具在渲染之间无法正确更新。

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

于 2019-08-05T07:24:46.503 回答