React useEffect获取错误-缺少依赖项

我尝试使用useEffect,但出现如下所示的错误,

React Hook useEffect has a missing dependency: 'data'. Either include it or remove the dependency array

这是我的组成部分

let id = props.location.pathname.split("--")[1];
let str = props.location.pathname.split("--")[0].substr(1);
const data = {id: id,link: str}

const [title,setTitle] = useState("")

useEffect(() => {
    setTitle("...") // Yükleniyor.
    async function getTitle() {             
        axios.post('/api/data/entry/get',data)
        .then(res => {
        setTitle(res.data.title)
        // TODO: Catch ekle.
        })
    }
    getTitle()
},[props])
jackybye 回答:React useEffect获取错误-缺少依赖项

您必须在依赖项数组中包括“数据”。这是因为您的挂钩在其回调中使用了它。

这样,每次更改依赖项数组中的变量之一时,就会调用该挂钩。

我注意到“数据”对象使用了组件属性中的值。您可能会说“好吧,那我为什么还要同时包含prop和数据?”那么,在定义依赖项数组时,您需要尽可能地精细。让它依靠道具太笼统了。就您而言,应该使它仅依赖于“数据”

编辑

我错过了一个事实,如果您要添加data作为依赖项,则该挂钩将在每次重新渲染时触发。这是因为data基本上是每个渲染的新对象。您可以将data的成员分为多个变量,并将其用作依赖项:

您的组件现在看起来像这样:

const id = props.location.pathname.split("--")[1];
const str = props.location.pathname.split("--")[0].substr(1);

const data = useRef({id: id,link: str});

const [title,setTitle] = useState("")

useEffect(() => { /* ... */ },[id,str]);

请注意,我尚未测试代码。请查看是否可行。

,

您必须将数据添加到依赖项列表中,如下所示

let id = props.location.pathname.split("--")[1];
let str = props.location.pathname.split("--")[0].substr(1);
const data = {id: id,link: str}

const [title,setTitle] = useState("")

useEffect(() => {
    setTitle("...") // Yükleniyor.
    const getTitle = async () => {
      const res = await 
        axios.post('/api/data/entry/get',data)
        setTitle(res.data.title)
        // TODO: Catch ekle.
        };
    getTitle()
},[props])
本文链接:https://www.f2er.com/3139641.html

大家都在问