React Material UI CardMedia 问题

时间:2021-04-08 08:11:01

标签: reactjs material-ui

enter image description here

我用 CardMedia 来显示图片,当我进入主页时,它不显示图片并且有一些错误。当我点击一些链接并使用浏览器中的“返回”按钮时,图像会返回。

我使用 getInitialProps() 在 Home 组件中获取图像 url 并作为属性传递给子 (Catalog) 组件。

我认为图像 url 将在 Home 组件中接收,然后 CardMedia 将从 Home 组件接收的图像呈现为道具。 有什么想法吗?


export default function Home({ categories }) {
 
    return (
        <div>
            <Header categories={ categories}/>
            <Carousel />
       
            <Catalog categories={ categories}/>
            <Footer/>
        </div>
    )
}

Home.getInitialProps = async () => {
    const response = await fetch('http://localhost:1337/categories/')
    const categories = await response.json();
    return {
      categories:categories
    }
  }
export default function Catalog(props) {
  const classes = useStyles();
  const cards = props.categories
  const server = 'http://localhost:1337'
  console.log(cards)
  return (
    <React.Fragment>
      <CssBaseline />

      <main>
        {/* Hero unit */}
        <div className={classes.heroContent}>
          <Container maxWidth="sm">
            <Typography component="h1" variant="h2" align="center" color="textPrimary" gutterBottom>
              Album layout
            </Typography>
            <Typography variant="h5" align="center" color="textSecondary" paragraph>
              Something short and leading about the collection below—its contents, the creator, etc.
              Make it short and sweet, but not too short so folks don&apos;t simply skip over it
              entirely.
            </Typography>
          </Container>
        </div>
        <Container className={classes.cardGrid} maxWidth="md">
          {/* End hero unit */}
          <Grid container spacing={4}>
            {cards.map((card) => (
              <Link as={`/products/${card.category}`} href='/products/[bathroom]' key={card.id}>
                <Grid item key={card.category} xs={12} sm={6} md={4} >
                  <Card className={classes.card}>
                    <CardMedia
                      className={classes.cardMedia}
                      image={server+ card.img.url}
                      category={card.category}

                    />
                    <CardContent className={classes.cardContent}>
                      <Typography gutterBottom variant="h5" component="h2">
                        {card.category}
                      </Typography>
                      <Typography>
                        Product description.
                    </Typography>
                    </CardContent>

                  </Card>
                </Grid>
              </Link>


            ))}
          </Grid>
        </Container>
      </main>
      {/* Footer */}

      {/* End footer */}
    </React.Fragment>
  );
}

1 个答案:

答案 0 :(得分:1)

事实证明,Next.js 中的 CSS 渲染有点不同。 请参阅此文档 https://material-ui.com/guides/server-rendering/