【问题标题】:How can fix the warning errors present in the dependency array of the useEffect如何修复 useEffect 的依赖数组中存在的警告错误
【发布时间】:2020-11-04 11:25:18
【问题描述】:

我想解决我项目中的所有警告,但我不知道我应该在依赖项数组中包含哪些依赖项。下面我分享代码:

import React, { useState, useEffect } from 'react';
import { Redirect } from 'react-router-dom';
import Layout from '../components/Layout';
import { getPicture, getAlbums, updatePicture } from './ApiAdmin';

const UpdatePicture = ({ match }) => {

 ...

 const init = (pictureId) => {
    getPicture(pictureId).then(data => {
        if (data.err) {
            setValues({ ...values, err: data.err })
        } else {
            // populate the state
            setValues({
                ...values,
                name: data.name,
                album: data.album._id,
                formData: new FormData()
            })
            initAlbums()
        }
    })
 }

 const initAlbums = () => {
    getAlbums().then(data => {
        if (data.err) {
            setValues({
                ...values,
                error: data.err
            });
        } else {
            setValues({
                albums: data,
                formData: new FormData()
            });
         }
    });
 }

 const redirectUser = () => {
    if (redirectToProfile) {
        if (!error) {
            return < Redirect to="/" />
        }
     }
  }

 useEffect(() => {
    init(match.params.pictureId);
    redirectUser(); // allows display the changes when a picture is updated
 }, []);

...


}

这是抛出我的警告:

React Hook useEffect 缺少依赖项:“init”、“match.params.pictureId”和“redirectUser”。要么包含它们,要么删除依赖数组 react-hooks/exhaustive-deps

感谢谁能帮我解决这个问题。

【问题讨论】:

标签: reactjs react-hooks use-effect


【解决方案1】:

【讨论】:

    【解决方案2】:

    只需将它们包含在您的依赖数组中

    useEffect(() => {
        init(match.params.pictureId);
        redirectUser(); // allows display the changes when a picture is updated
     }, [init, match.params.pictureId, redirectUser]);
    

    这些都是当它们发生变化时应该调用新的 useEffect 运行的东西。我建议让initredirectUser 函数使用useCallback,这样它们就不会在每个渲染上运行useEffect,除非它们发生变化(它们也会有依赖数组!)。

    【讨论】:

    • 您好@Diesel,感谢您抽出宝贵时间!但是当我添加依赖项时,在终端出现这个错误:编译失败。第 32:9 行:'init' 未定义 no-undef 第 32:15 行:'match' 未定义 no-undef 第 32:39 行:'redirectUser' 未定义 no-undef
    • 算了,使用 useCallback 我能够解决警告。谢谢
    猜你喜欢
    • 2021-07-12
    • 1970-01-01
    • 2020-11-24
    • 2019-10-16
    相关资源
    最近更新 更多