有没有办法使用 preact 信号效果函数,让我可以选择我想要订阅的信号?

问题描述 投票:0回答:1

我有这个代码。

effect(() => {
        productsShoes.value = shoes.value
})

我想,只有每次shoes.value改变时,才会触发这个效果。也就是说,它的重新渲染,要么两个信号都改变了。

我想要实现的逻辑是这样的 useEffect Reacts hook:

    useEffect(() => {
        productsShoes.value = shoes.value
    }, [shoes.value])

首先感谢您的关注!

reactjs signals preact-signal
1个回答
0
投票

To run arbitrary code in response to signal changes, we can use effect(fn). Similar to computed signals, effects track which signals are accessed and re-run their callback when those signals change. If the callback returns a function, this function will be run before the next value update. Unlike computed signals, effect() does not return a signal - it's the end of a sequence of changes.

When responding to signal changes within a component, use the hook variant: useSignalEffect(fn).

https://preactjs.com/guide/v10/signals/#effectfn

这意味着对于您的情况更喜欢 useSignalEffect,无需传递任何依赖项,它已经跟踪您的更改并自动运行

© www.soinside.com 2019 - 2024. All rights reserved.