mithriljs 组件状态不为回调或承诺更新

mithriljs component state not update for callback or promise

我这样使用 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 函数,callback/promise 从中更新 UserFullname。 但它不起作用。我尝试用 setTimeout 简化它,它仍然不起作用。

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

谢谢

Mithril will not know to redraw once the data changes have taken place - so you'll need to tell it to by calling m.redraw()getUserFullname 函数体的末尾。

您目前所在的位置:

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

您应该改为:

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

    m.redraw();
  }, 1000);
}

Here's a working demo with the fix highlighted.