簡體   English   中英

React Hook useEffect 缺少 object 的依賴項

[英]React Hook useEffect missing dependency for object

我將我的 object 拆分為依賴項,但現在 eslint 顯示缺少依賴項的警告。

const MyComp = () => {
    const data = {name:'ss', age: 1}

    useEffect(() => {

    }, [data.name, data.age])

    return <div>content</div>
}

我無法放置整個data以避免不必要的重新渲染。

聽起來您在鈎子中使用data 您說過您不能將data本身添加為依賴項,因為它會導致過多的渲染。 這意味着您需要拆分data

const MyComp = () => {
    const name ='ss'
    const age = 1

    useEffect(() => {
        // Use `name` and `age` here
    }, [name, age])

    return <div>content</div>
}

When using hooks, you generally want to prefer separate state members (I assume data is a state member, not really a constant) over using an object state member.

或者另一種方式,正如邁克爾 H 指出的那樣

const MyComp = () => {
    const data = {name: 'ss', age: 1}

    const {name, age} = data // <=========================
    useEffect(() => {
        // Use `name` and `age` (not `data`) here
    }, [name, age])          // <=========================

    return <div>content</div>
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM