ReactJS-如何在ReactJS材质表中加载和映射数据

时间:2019-08-05 07:19:10

标签: reactjs mapping loaddata react-material

如何在reactjs材料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>
    );
  }

1 个答案:

答案 0 :(得分:1)

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

this.rows = props.value.cargo;

然后使用this.rows而不是rows进行访问。

但是,对于这个示例,这毫无用处,并且将来在渲染之间道具无法正确更新的情况下还会给您带来其他问题。

您应使用this.props.value.cargo.map中的rows.map而不是render()。如果您想使其更整洁,也可以在const rows内创建另一个render()。可以使用相同的名称,因为它们属于不同的范围。