[英]React Hook useEffect has a missing dependency. Why am I getting this error when nothing is broken?
not sure what is causing me to get this React error.不知道是什么导致我得到这个 React 错误。 My application works and my URL slugs are in affect and working, however this error is popping up and I'm not entirely sure why?
我的应用程序工作正常,我的 URL slug 正在影响和工作,但是这个错误正在弹出,我不完全确定为什么?
Full Error:
Line 30:5: React Hook useEffect has a missing dependency: 'slug'. Either include it or remove the dependency array react-hooks/exhaustive-deps
All I'm trying to do is pass API data to my page for rendering and creating a URL parameter with my slug
我要做的就是将 API 数据传递到我的页面,以使用我的
slug
渲染和创建 URL 参数
import React, { useState, useEffect } from 'react';
import axiosInstance from '../axios';
import { useParams } from 'react-router-dom';
//MaterialUI
import CssBaseline from '@material-ui/core/CssBaseline';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
import Typography from '@material-ui/core/Typography';
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(8),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
}));
export default function Bucket() {
const { slug } = useParams();
const classes = useStyles();
const [data, setData] = useState({ bucket: [] });
useEffect(() => {
axiosInstance.get(slug).then((res) => {
setData({ bucket: res.data });
console.log(res.data);
});
}, [setData]); //this is where the error is
return (
<Container component="main" maxWidth="md">
<CssBaseline />
<div className={classes.paper}></div>
<div className={classes.heroContent}>
<Container maxWidth="sm">
<Typography
component="h1"
variant="h2"
align="center"
color="textPrimary"
gutterBottom
>
{data.bucket.title}
</Typography>
<Typography
variant="h5"
align="center"
color="textSecondary"
paragraph
>
{data.bucket.about}
</Typography>
</Container>
</div>
</Container>
);
}
Thank you for the debugging help!感谢调试帮助!
You just add it into the dependency array.您只需将其添加到依赖项数组中。 I will further clarify that
slug
needs to be a dependency because you want the useEffect to run again if it changes.我将进一步澄清
slug
需要成为一个依赖项,因为您希望 useEffect 在它发生变化时再次运行。
useEffect(() => {
axiosInstance.get(slug).then((res) => {
setData({ bucket: res.data });
console.log(res.data);
});
}, [setData, slug]);
You aren't using slug
anywhere apart from the effect, simply move it into the effect to get rid of this error.除了效果之外,您没有在任何地方使用
slug
,只需将其移动到效果中即可消除此错误。
useEffect(() => {
axiosInstance.get(slug).then((res) => {
setData({ bucket: res.data });
console.log(res.data);
});
}, [slug,setData]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.