You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React首次加载useEffect调用API多次且报错问题求助

React代码修复:渲染报错与API重复调用问题

问题1:首次加载/刷新时渲染报错

原因:组件初始化时data的状态为null,此时直接访问data.advice会触发Cannot read properties of null错误。

修复方案:

  • 使用可选链操作符(?.),当data为null或undefined时,表达式会返回undefined而非报错:
    {data?.advice}
    
  • 或者添加条件渲染,确保仅当data存在时才渲染对应内容:
    {data && <Typography variant="body2" color="text.secondary">{data.advice}</Typography>}
    

问题2:API被调用两次

原因:React 18的Strict Mode在开发环境下会重复执行useEffect等副作用函数,用于提前检测潜在的副作用问题,生产环境不会出现此情况。

修复方案:

  • 若仅想在开发环境避免两次调用,可在项目入口文件(如index.js)中移除<StrictMode>的包裹;
  • 接受开发环境的该行为,因为它不会影响生产环境的运行逻辑。

修改后的完整代码

import { Box, Button, Card, CardActions, CardContent, Container, Typography } from '@mui/material';
import axios from 'axios';
import React, { useEffect, useState } from 'react';

const Advice = () => {
    const [data, setData] = useState(null);
    const clicked = () => {
        callAPI();
    }
    const callAPI = () => {
        axios.get('https://api.adviceslip.com/advice')
            .then(response => {
                setData(response.data.slip)
                console.log(response.data.slip);
            })
            .catch((error) => {
                console.log(error);
            })
    }
    useEffect(() => {
        callAPI();
    }, [])
    return (
        <Box>
            <Container>
                <Typography variant='h2' sx={{ textAlign: "center" }}>Advice App</Typography>
                <Card sx={{ maxWidth: 500, margin: "10px auto", display: "block", textAlign: "center" }}>
                    <CardContent>
                        <Typography gutterBottom variant="h5" component="div">
                            Advice of the Day
                        </Typography>
                        <Typography variant="body2" color="text.secondary">
                            {data?.advice}
                        </Typography>
                    </CardContent>
                    <CardActions>
                        <Button size="small" onClick={clicked}>Share</Button>
                        <Button size="small">Learn More</Button>
                    </CardActions>
                </Card>
            </Container>
        </Box>
    );
};

export default Advice;

内容的提问来源于stack exchange,提问作者Shoaib Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 12:53:27