繁体   English   中英

在 React 中使用 Axios 获取 API

[英]Fetch API with Axios in React

const key = '618479acc2ef5ba8018516ac'


 function UserPost1 () {
    const [post, setPost] = useState(['']);

    const handleExpandClick = () => {
      setExpanded(!expanded);
    };



     useEffect(() =>{
    axios.get('https://dummyapi.io/data/v1/post' , { headers: { 'app-id': key } })
    .then(res => {
        setPost(res.data.data)
        console.log(res)
    })
    .catch(err =>{
        console.log(err)
    })
},[]);

    return(
        <div className="Post-style">
        {post.map(post =>(
           <Box sx={{ flexGrow: 1 }}>
            <Grid container rowSpacing={0} columnSpacing={{ xs: 1, sm: 2, md: 2, lg: 2 }}  >
                <Grid 
                    container
                    direction="row"
                    justifyContent="center">
                    <Grid item xs={4} sm={12} md={6} lg={4}>
                    <div className="card-Style">
                    <Card sx={{ width: 355}} style={{backgroundColor: "aquamarine"}} >
                            <CardHeader
                            avatar={
                                <Avatar 
                                src={post.owner.picture}
                                />
                            }
                            action={
                            <IconButton aria-label="settings">
                                <MoreVertIcon />
                            </IconButton>
                            }
                            title={post.owner.firstName + " " + post.owner.lastName}
                            subheader={post.publishDate}
                            />
                        <CardMedia
                            component="img"
                            height="194"
                            image={post.image}
                            alt="Paella dish"
                            backgroundcolor="blue"
                            />
                        <CardContent>
                            
                            <Typography variant="body2" color="text.secondary">
                            {post.text}
                            <br></br>
                            {post.likes}
                            <br></br>
                            {post.tags}
                            </Typography>
                        </CardContent>
 
                    </Card>
                    </div>
                </Grid>
                </Grid>
            </Grid>
            </Box>
            ))}
        </div>
    )
}

export default UserPost1;

当我运行这段代码时,我无法使用 Axios 从 API 获取数据,它说错误无法读取未定义的属性(读取“图片”)。 我试图捕捉错误,但它没有显示在控制台日志中。 我该如何解决这个问题。

我应该让 axios 等待它获取数据 API 还是让它为 false。 我该怎么办,这是我第一次使用 API。

不知何故,所有者对象中缺少图片属性。 在图片前添加可选链接。

                        <CardHeader
                        avatar={
                            <Avatar 
                            src={post.owner?.picture}
                            />
                        }

在完成异步查询并设置状态值后呈现您的帖子组件。 使用条件渲染并将默认状态值从 [''] 更改为 null。

要在查询执行期间排除布局跳转,请创建占位符。 在请求运行时显示占位符,在请求完成并将值设置为状态后,显示post组件。 祝你好运!

// change default useState value
const [post, setPost] = useState(null);

// add condition rendering
{post ? post.map(post => (
    <Box sx={{ flexGrow: 1 }}>
      <Grid container rowSpacing={0} columnSpacing={{ xs: 1, sm: 2, md: 2, lg: 2 }}  >
        <Grid
          container
          direction="row"
          justifyContent="center">
          <Grid item xs={4} sm={12} md={6} lg={4}>
            <div className="card-Style">
              <Card sx={{ width: 355 }} style={{ backgroundColor: "aquamarine" }} >
                <CardHeader
                  avatar={
                    <Avatar
                      src={post.owner.picture}
                    />
                  }
                  action={
                    <IconButton aria-label="settings">
                      <MoreVertIcon />
                    </IconButton>
                  }
                  title={post.owner.firstName + " " + post.owner.lastName}
                  subheader={post.publishDate}
                />
                <CardMedia
                  component="img"
                  height="194"
                  image={post.image}
                  alt="Paella dish"
                  backgroundcolor="blue"
                />
                <CardContent>
                  <Typography variant="body2" color="text.secondary">
                    {post.text}
                    <br></br>
                    {post.likes}
                    <br></br>
                    {post.tags}
                  </Typography>
                </CardContent>
              </Card>
            </div>
          </Grid>
        </Grid>
      </Grid>
    </Box>
  )) : <div> PLACEHOLDER </div>}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM