英文:
SolidJS: Using createEffect to observe signal changes
问题
我已经在Angularverse中度过了自Angular 2以来的新旅程
我一直在关注他们官方网站上的Effects教程,但我无法使它按我想要的方式工作。
我以为createEffect
会跟踪并在每次计数信号更改时运行,或者我是从这里理解的:
该效果自动订阅在函数执行期间读取的任何信号,并在其中任何一个更改时重新运行。
不幸的是,点击按钮似乎没有任何效果。那么,我漏掉了什么?
import { render } from "solid-js/web";
import { createSignal, createEffect } from "solid-js";
function Counter() {
const [count, setCount] = createSignal(0);
const doubleCount = () => setCount(count() * 2);
createEffect(() => {
console.log("现在的计数是", count());
});
return <button onClick={doubleCount}>点击我</button>;
}
render(() => <Counter />, document.getElementById('app'));
英文:
I have started a new journey with SolidJS after being in the Angularverse since Angular 2
I've been following the Effects tutorial on their official website but I'm not able to make it work the way I want.
I thought createEffect
would keep track and run every time the count signal changed, or so I understood from here:
> The effect automatically subscribes to any signal that is read during
> the function's execution and reruns when any of them change.
Unfortunately, clicking the button doesn't seem to have any effect. So, what am I missing?
import { render } from "solid-js/web";
import { createSignal, createEffect } from "solid-js";
function Counter() {
const [count, setCount] = createSignal(0);
const doubleCount = () => setCount(count() * 2);
createEffect(() => {
console.log("The count is now", count());
});
return <button onClick={doubleCount}>Click Me</button>;
}
render(() => <Counter />, document.getElementById('app'));
答案1
得分: 2
这是一个特性!
发生的情况是 0 * 2 = 0,所以不会触发任何效果,因为 count 的值没有改变。
尝试使用以下代码:
const [count, setCount] = createSignal(1);
通过点击来查看每次数值变化时的 console.log。
英文:
It is a feature !
What is happening is that 0 * 2 = 0 so it doesn't trigger any effect because the value of count didn't change.
Try
const [count, setCount] = createSignal(1);
to see a console.log each time the value change with your click
答案2
得分: 0
你的代码是正确的并且按预期运行。可能有两个原因导致你看不到变化:
- 如果没有日志输出,那意味着页面上没有
#app
元素。 - 如果只有一个日志但后续没有其他日志,那是因为 0*2 等于 0,数值没有改变,所以不会触发重新运行。
链接:https://playground.solidjs.com/anonymous/7ec9c592-6c30-43a0-97a7-5f26917b4334
英文:
Your code is correct and runs as expected. Two possible reason why you don't see change:
- If tere is no log, it means you don't have #app element on the page.
- If there is only one log but no subsequent ones, that is because 0*2 is 0, value does not change, so it does not trigger re-run.
https://playground.solidjs.com/anonymous/7ec9c592-6c30-43a0-97a7-5f26917b4334
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论