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
相关产品推荐
相关产品推荐

