[英]Accessing parent state within function called by EventListener in child's useEffect
I have a component that looks something like this:我有一个看起来像这样的组件:
const [someState,setSomeState] = useState()
const onResize = (data) => {
// do some stuff with someState
}
return <MyContainer onResize={onResize}>
... various children
</MyContainer>
The MyContainer
component looks kinda like this: MyContainer
组件看起来像这样:
const MyContainer = ({onResize}) => {
useEffect(() => {
addEventListener((data) => {
onResize(data)
})
return cleanUpListener()
}, [])
// ...
}
My problem is that inside my first component inside onResize()
someState
is not up-to-date.我的问题是在onResize()
someState
第一个组件中不是最新的。 I understand that useEffect()
creates a closure and so i can only access values of state on initialization.我知道useEffect()
创建了一个闭包,所以我只能在初始化时访问状态值。 I think I could add onResize
as a dependency of the useEffect()
, but this seems not great because then my event listener will be destroyed and recreated very frequently.我想我可以将onResize
添加为useEffect()
的依赖项,但这似乎不太好,因为那样我的事件侦听器将非常频繁地被销毁和重新创建。
What i am looking for is a clean way to create a single event listener on component mount, be able to access state inside it's callback, and have it teardown on unmount.我正在寻找的是一种在组件安装上创建单个事件侦听器的干净方法,能够访问其回调中的状态,并在卸载时将其拆解。 I have tried many things and looked around quite a bit and it seems strange that there is no solution to this.我尝试了很多东西并环顾四周,似乎很奇怪没有解决方案。 I am fairly new to react so i am hoping someone more experienced can point me to an elegant way to do something like this.我对反应还很陌生,所以我希望更有经验的人可以为我指出一种优雅的方式来做这样的事情。
I am not 100% sure what you want, but you can pass someState
as a prop to your child component.我不是 100% 确定您想要什么,但是您可以将someState
作为道具传递给您的子组件。 The add that as a dependency for your useEffect
, and pass that as a parameter for onResize
if needed.添加它作为useEffect
的依赖useEffect
,并在需要时将其作为onResize
的参数传递。 As long as you are not mutating the value, it should be fine.只要您不改变该值,就应该没问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.