【发布时间】:2021-05-04 08:53:41
【问题描述】:
我有一个父组件
import React ,{useState} from 'react'
import ChildComponenet from './child'
export default function App() {
const [parentValue , setParentValue] = useState(0)
const someParentfunc = (input1,input2)=>{
setParentValue( parseInt(input1,10) +parseInt(input2,10))
}
return (
<div className="App">
Add : {parentValue}
<ChildComponenet someParentfunc={someParentfunc} />
</div>
);
}
现在是子组件:
import React ,{useState,useEffect} from 'react'
function ChildComponenet({someParentfunc}) {
const [input1 , setInput1] = useState(10)
const [input2 , setInput2] = useState(20)
useEffect(() => {
someParentfunc(input1,input2)
}, [input1,input2])
return (
<div>
<input type="text"
value={input1}
onChange={event => setInput1(event.target.value) }
/>
<input type="text"
value={input2}
onChange={event => setInput2(event.target.value) }
/>
</div>
)
}
export default ChildComponenet
错误是:React Hook useEffect 缺少依赖项:'someParentfunc'。要么包含它,要么移除依赖数组。
我是否应该在 useEffect 中添加 someParentfunc ,这是正确的方法吗:
useEffect(() => {
someParentfunc(input1, input2);
}, [input1, input2,someParentfunc]);
工作项目链接是:https://codesandbox.io/s/competent-kare-kce02?file=/src/child.js
【问题讨论】:
-
你在谷歌上发现了什么?
-
是的,这是正确的方法——你不应该从
useEffect钩子的依赖数组中省略任何依赖。将someParentfunc包裹在useCallback钩子中,然后在子组件中,添加到useEffect钩子的依赖数组中 -
medium.com/@infinitypaul/… 本文详细阐述了@Yousaf 的建议。将其包装在 useCallback 中是一种更好的做法。
标签: reactjs react-hooks react-props use-effect