[英]React - Updated prop in custom hook
I have a custom hook that gives me a certain percentage of the scroll.我有一个自定义钩子,可以给我一定比例的滚动。 I takes the values from the state-management solution Zustand.
我从状态管理解决方案 Zusand 中获取值。 I'm using it inside a component to update some styles on elements on the page.
我在组件中使用它来更新页面元素上的一些 styles。
The problem is that I only want to update these elements on a certain condition passed as prop of my component.问题是我只想在作为组件的道具传递的特定条件下更新这些元素。 And these conditions are not updated in my hook.
而这些条件并没有在我的钩子中更新。
I don't know how I should change it in order to get the updated condition.我不知道我应该如何更改它以获得更新的条件。
import create from 'zustand'
const useStore = create(() => {
scroll: 0
})
const useScroll = (callback: (scroll: number) => void): null => {
const subscribe = useRef()
useEffect(() => {
if (subscribe & subscribe.current) {
// Unsubscribe
subscribe.current()
}
subscribe.current = useStore.subscribe(() => {
callback(useStore.getState().scroll)
})
}, [subscribe])
return null
}
const myComponent = (condition: Boolean) => {
console.log(condition) // gives the updated value of the prop
useScroll(() => {
console.log(condition) // is not updated
})
}
My guess is that you need to add the callback
parameter to the list of properties useEffect
is watching:我的猜测是您需要将
callback
参数添加到useEffect
正在观看的属性列表中:
useEffect(() => {
...
}, [subscribe, callback])
That way, whenever the function callback
changes because of a new condition, the useEffect will re-run.这样,每当 function
callback
由于新条件而发生变化时,useEffect 都会重新运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.