mithriljs组件状态未针对回调或Promise更新

时间:2019-07-15 10:31:09

标签: javascript mithril.js

我这样使用mithriljs组件状态:

const Dashboard = () => {
    let ExpenseAmount = 0;
    let IncomeAmount = 0;
    let UserFullname = '';

    const getExpense = () => {
        ExpenseAmount = 1000;
    };

    const getIncome = () => {
        IncomeAmount = 2000;
    };

    const getUserFullname = () => {
        setTimeout(() => {
            console.log('calling fullname');
            UserFullname = 'Mike'; //<----
        }, 1000);
    }

    getUserFullname();

    return {
        view: () => [
            m("div", { class: "container-fluid flex-grow-1 container-p-y" }, [
                m(
                    "h4",
                    {
                        class:
                            "media align-items-center font-weight-bold py-3 mb-4"
                    },
                    [
                        m("img", {
                            src: "assets/img/avatars/1.png",
                            class: "ui-w-50 rounded-circle"
                        }),
                        m("div", { class: "media-body ml-3" }, [
                            m("span", `Welcome back, ${UserFullname}!`),
                            m(
                                "div",
                                { class: "text-muted text-tiny mt-1" },
                                m(
                                    "small",
                                    { class: "font-weight-normal" },
                                    `Today is ${new Date().toDateString()}`
                                )
                            )
                        ])
                    ]
                )
            ])
        ]
    };
};

我希望可以调用和ajax函数,并从中进行回调/承诺将更新UserFullname。 但这行不通。我尝试使用setTimeout对其进行简化,但仍然无法正常工作。

如何解决ajax调用或priomise或setTimeout中的更新状态?

谢谢

1 个答案:

答案 0 :(得分:1)

数据更改发生后,秘银will not know to redraw-因此您需要通过在use函数体末尾调用m.redraw()来告知它。

您当前所在的位置:

getUserFullname

您应该写:

const getUserFullname = () => {
  setTimeout(() => {
    UserFullname = 'Mike';
  }, 1000);
}

Here's a working demo with the fix highlighted