如何将初始化数据发送到 Mithril 组件

How can I send init data to a Mithril component

我正在尝试通过设置 ID 来初始化 Mithril 组件以从服务器获取数据,如下所示:

// view/UserList.js
module.exports = {
    oninit: function(vnode) {
        console.log(vnode);
        var groupId = vnode.attrs.groupId;
        console.log('The group ID is '+groupId);
        User.loadUsersInGroup(groupId);
    },
    view: ...
}

我有以下内容:

var userList = require('./view/UserList');
m.mount(document.body, UserList, {groupId: 5});

但我得到:

vnode.attrs is undefined

我尝试将其更改为:

var UserList = require('./view/UserList');
m.mount(document.body, m(UserList, {groupId: 5}));

但现在我得到:

m.mount(element, component) expects a component, not a vnode

如何才能正确填充 vnode.attrs?

可以在 https://mithril.js.org/mount.html#description.

中找到向组件发送初始化数据的正确方法

To pass arguments when mounting a component use:

m.mount(element, {view: function () {return m(Component, attrs)}})

因此应用于这种情况,它将是:

m.mount(document.body, {view: function() { return m(UserList, {groupId: 5}); }});

其他一些方法是:

const full   = {view: vnode => m('h1', vnode.attrs.test)}
const short  = {view: v => m('h1', v.attrs.test)}
const dest   = {view: ({attrs}) => m('h1', attrs.test)}
const destf  = {view: ({attrs: {test}}) => m('h1', test)}

m.mount(document.body, {
  view: () => [
    m(full,  {test: "full"}),
    m(short, {test: "short"}),
    m(dest,  {test: "destructured"}),
    m(destf, {test: "fully destructured"})
  ]
})

See them in action here.(由 osban 在 Mithril.js Gitter 聊天中提供)