【问题标题】:Svelte - store auto subscription - value does not get updatedSvelte - 商店自动订阅 - 值未更新
【发布时间】:2021-12-26 20:23:08
【问题描述】:

我有 3 个与此问题有关的文件。一个是组件文件,一个是JS库文件,一个是store文件。

存储文件:

import { writable } from "svelte/store";

export const appStore = writable({
    currentPage : '',
});

库文件:

import { appStore } from "../stores/appStore";

let store;

appStore.subscribe(data => {
    store = data;
});

export async function post() {
    console.log(store);
}

最后是组件文件:

import { test } from '$lib/req_utils';
import { appStore } from "../../stores/AppStore";

appStore.update(store => {
    store.currentPage = 'login';
    return store;
});

function handleLogin() {
    test();
}

基本上,当组件文件被加载时,store 中的 currentPage 被设置为 'login' 并且当 handleLogin 事件被触发时。在我的库 JS 中调用了测试函数,库 JS 将输出 appStore.currentPage 的值 - 正确的将是“登录”。

但是,当我尝试在组件文件中使用自动订阅时,如下所示:

import { test } from '$lib/req_utils';
import { appStore } from "../../stores/AppStore";

$appStore.currentPage = 'login';

function handleLogin() {
    test();
}

商店似乎没有更新(在库 JS 中检查 test() 中的值时)

根据我看过的文档和教程,上面应该可以工作吗?

【问题讨论】:

    标签: svelte


    【解决方案1】:

    看起来,由于 Svelte 反应性是基于赋值的,因此将值分配给对象的属性不会触发反应性。但是,I've set up a demo of your case in the Svelte REPL 似乎工作正常。

    也许这与测试功能有关?我不得不说这对我来说似乎很奇怪,因为您声称 update 方法确实有效。

    我想到的导致问题的其他一些想法是,currentPage 属性在某处被重置。或者可能是测试函数的编写方式,store 变量在初始化时绑定。无论哪种方式,我相信使用update$ 应该是相同的。

    This GitHub issue 可能有相关信息,但我没有找到任何信息。

    【讨论】:

      猜你喜欢
      • 2020-07-29
      • 2020-04-27
      • 2021-08-09
      • 2021-02-27
      • 2019-06-12
      • 2021-12-23
      • 2022-12-18
      • 2018-02-16
      • 2017-11-09
      相关资源
      最近更新 更多