【问题标题】:Reactjs - How to load and map data in reactjs material tableReactjs - 如何在 reactjs 材料表中加载和映射数据
【发布时间】:2019-12-12 16:43:53
【问题描述】:

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

【问题讨论】:

    标签: reactjs mapping loaddata react-material


    【解决方案1】:

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

    this.rows = props.value.cargo;
    

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

    但是,对于这个示例,这没有任何意义,并且会在未来给您带来其他问题,因为 props 在渲染之间无法正确更新。

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

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 2020-12-05
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      相关资源
      最近更新 更多