英文:
Reactive function in svelte not firing when the value changes?
问题
以下是您要翻译的内容:
整个代码示例如下。
我遇到的问题是,我知道vatSuccess实际上已经成功更改。但是,当我尝试以响应方式进行任何操作时,我知道它应该是true时,它似乎不起作用。
在下面的示例中,我希望响应语句将"vatSuccess"记录在控制台上运行两次,首先在将其声明为false时运行,然后在其变为true时再次运行。
但它只运行一次。
let vatSuccess = false
let nameSuccess = false
function handleVatValidation(): Error {
// VAT是可选的,所以不填写也会通过验证
if (companyInformation.vat.length === 0) {
vatSuccess = true
vatError = null
return null
}
if (companyInformation.vat.length < 6) {
vatSuccess = false
vatError = 'VAT必须至少为6个字符'
return 'VAT必须至少为6个字符'
}
vatSuccess = true
console.log('vatSuccess', vatSuccess) // 此代码运行并打印true
vatError = null
return null
}
$: {
console.log('vatSuccess', vatSuccess) // 这只在它为false时运行一次
}
我已经尝试过像这样更改它,使vatSuccess一开始就成为一个响应值,但行为仍然相同。
$: vatSuccess = false
请注意,这是您的翻译,不包含代码部分。
英文:
Entire code sample below.
The problem I have is that I know vatSuccess is actually changing successfully. However when I try to do anything with it in a reactive manner when I know it should be true it does not seem to work.
In the sample below I would expect the reactive statement console logging 'vatSuccess' to run twice first when it's declared as false and then again when it becomes true.
However it only runs the first time
let vatSuccess = false
let nameSuccess = false
function handleVatValidation(): Error {
// Vat is optional so putting nothing passes validation
if (companyInformation.vat.length === 0) {
vatSuccess = true
vatError = null
return null
}
if (companyInformation.vat.length < 6) {
vatSuccess = false
vatError = 'vat must be at least 6 characters'
return 'vat must be at least 6 characters'
}
vatSuccess = true
console.log('vatSuccess', vatSuccess) // This code runs and prints true
vatError = null
return null
}
$: {
console.log('vatSuccess', vatSuccess) // This only runs once when it is false
}
I have tried to change it liek this so vatSuccess is a reactive value to begin with but the behaviour is the same.
$: vatSuccess = false
答案1
得分: 1
函数不会调用自身,函数内部读取的任何变量都不会影响响应性。
如果函数在模板(组件的HTML部分)中被调用,或者在响应式块($: ...
)中被调用,它将在函数本身发生变化或其中一个参数发生变化时重新评估。
这个函数依赖于 companyInformation
,但这并不 "可见"。要么将其变成一个参数,要么将整个函数本身声明为响应式:
$: handleVatValidation = () => {
...
}
($: vatSuccess = false
不起作用,因为它不包含会导致重新评估的额外依赖项。)
英文:
Functions do not call themselves and any variable being read inside the function has no bearing on reactivity.
If the function is called in the template (HTML part of a component) or a reactive block ($: ...
), it will be re-evaluated if the function itself changes or one of the arguments.
This function has a dependency on companyInformation
but this is not "visible". Either turn that into an argument or declare the entire function itself reactively:
$: handleVatValidation = () => {
...
}
($: vatSuccess = false
does nothing because it contains no additional dependencies that would cause a re-evaluation.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论