使用PrevProps时如何将ComponentDidupDate转换为使用效果
我有一个遗产 preaeAct (不是错字)组件,我试图重构使用钩子而不是基于类的组件。我遇到了一个障碍,因为在componentDidupdate中它仅引用prevprops
而不是任何特定的道具。遗产生命周期方法看起来像这样:
componentDidUpdate(prevProps) {
addListenersFromProps(this.layer, this.props, {
filter: ({ prop }) => !prevProps[prop],
});
removeListenersFromProps(this.layer, prevProps, {
filter: ({ prop }) => !this.props[prop],
});
}
我的useffect
看起来像这样:
useEffect(() => {
addListenersFromProps(layer, props, {
filter: ({ prop }) => ?
});
removeListenersFromProps(layer, ?, {
filter: ({ prop }) => ?
});
}, [?]);
我不确定要添加到useffeft
hook的依赖项数组中,我不确定如何要调用removelisTenersFromProps
,因为它采用PrevProps
。
//编辑:
根据第一个评论,我可以做一些简单的事情:
// track props
const [_props, setProps] = useState(props);
useEffect(() => {
addListenersFromProps(layer, props, {
filter: ({ prop }) => !_props[prop],
});
removeListenersFromProps(layer, _props, {
filter: ({ prop }) => !props[prop],
});
setProps(props);
});
I have a legacy preact (not a typo) component I am trying to refactor to use hooks instead of class based components. I have run into a snag because in the componentDidUpdate it only references prevProps
and not any specific prop. The legacy life cycle method looks like this:
componentDidUpdate(prevProps) {
addListenersFromProps(this.layer, this.props, {
filter: ({ prop }) => !prevProps[prop],
});
removeListenersFromProps(this.layer, prevProps, {
filter: ({ prop }) => !this.props[prop],
});
}
My useEffect
looks like this:
useEffect(() => {
addListenersFromProps(layer, props, {
filter: ({ prop }) => ?
});
removeListenersFromProps(layer, ?, {
filter: ({ prop }) => ?
});
}, [?]);
I am not sure what to add to the dependency array for the useEffect
hook and I am not sure how to call removeListenersFromProps
as it takes the prevProps
.
// EDIT:
Based on the first comment, could I do something as simple as this:
// track props
const [_props, setProps] = useState(props);
useEffect(() => {
addListenersFromProps(layer, props, {
filter: ({ prop }) => !_props[prop],
});
removeListenersFromProps(layer, _props, {
filter: ({ prop }) => !props[prop],
});
setProps(props);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的编辑非常接近解决方案。您应该将道具用作使用效率中的回调,并应将状态设置在使用Props值的内部使用效果。请记住使用效果不是
async
,因此您需要在内部创建async
函数才能使用我的逻辑You are pretty close to solution with your edit. You should use props as callback in useEffect and you should set states inside useEffect with props values. Keep in mind useEffect is not
async
so you need to createasync
functions inside to use my logic从评论和答案中获取建议,我决定进行以下操作:
Taking advice from both comments and answers I decided to do the following: