MUI:必须指定`image`或`src`属性 [英] MUI: either `image` or `src` property must be specified

查看:24
本文介绍了MUI:必须指定`image`或`src`属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来CardMedia在创建组件时需要一个图像。由于我通过componentDidMount(RestAPI)拉取图像数据,因此该组件已经挂载。

componentDidMount() {
   // get all items via category ID and owner ID 
    const restApi = new API({ url: 'api' })
    restApi.createEntity({ name: 'items' })
    // api/items/<categoryId>/<ownerId>
    restApi.endpoints.items.getTwo({ id_a: this.props.categoryId, id_b: this.props.ownerId }).then(({ data }) => this.setState({ appData: data }))
}



render() {
    const { classes } = this.props;
   
    let classNameHolder = [classes.redAvatar, classes.greenAvatar, classes.blueAvatar, classes.purpleAvatar];
    this.state.appData.map(element => {
        this.state.images.push(element.imageUrl);
    });

    return (
        <Card>
            <CardHeader
                avatar={
                    <Avatar aria-label="Recipe"
                        className={classNameHolder[Math.floor(Math.random() * classNameHolder.length)]}>
                        {this.props.userName.charAt(0).toLocaleUpperCase()}
                    </Avatar>}
                title={this.props.userName} disableTypography={true} />
            <CardActionArea disabled={this.state.images.length === 1 ? true : false}>
                <CardMedia
                    id={this.props.ownerId}
                    className={classes.media}
                    image={this.state.images[this.state.imageIndex]}
                    onClick={this.handleOnClick} />
            </CardActionArea>
        </Card >
    );
  }
 }

我可以将所有API上移一级,所以我使用道具来传递数据映像,但我想知道你们是否有什么优雅的解决方案。

推荐答案

或者您可以对组件本身进行简单检查,以避免重置状态,例如在内容加载时显示MUI微调器 这将修复警告并向用户显示良好的反馈

<>
  {imgUrl ? (
    <CardMedia
      component="img"
      alt="Contemplative Reptile"
      height="140"
      src={imgUrl}
      title="Contemplative Reptile"
    />
  ) : (
    <Spinner />
  )}
</>

这篇关于MUI:必须指定`image`或`src`属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆