路由更改时秘银组件不更新

Mithril component not updating when route changes

我正在使用 Mithril.js 创建我的个人 website/blog 作为单页应用程序。我网站上的所有页面和博文都是使用 PagePost 组件呈现的,并且根据 URL.[=20= 中的 :slug 加载正确的页面]

我遇到的问题是 每当我尝试在页面之间切换时,页面内容都不会更新。在 pages 和 posts 之间切换是可行的,因为我在 PagePost 组件之间交替。但是,当我尝试连续两次使用同一组件时,从 页到 页,它不会更新网页。

m.route(document.body, '/', {
  // `Home` is a wrapper around `Page`
  // so I can route to `/` instead of `/home`
  '/': Home,
  '/:slug': Page,
  '/blog/:slug': Post
});
const Home = {
  view() {
    return m(Page, { slug: 'home' });
  }
};

这里是Page组件(Post组件非常相似)。两个组件都正确呈现。

const Page = {
  content: {},
  oninit(vnode) {
    m.request({
      method: 'GET',
      url: 'content.json',
    }).then((response) => {
      Page.content = response.pages[vnode.attrs.slug];
    });
  },
  view() {
    if (Page.content) {
      return [
        m('#content', m.trust(Page.content.body))
      ];
    }
  }
};

为什么 Mithril 没有意识到 slug 发生了变化?

docs page for m.route 有适合您的解决方案。

When a user navigates from a parameterized route to the same route with a different parameter (e.g. going from /page/1 to /page/2 given a route /page/:id, the component would not be recreated from scratch since both routes resolve to the same component, and thus result in a virtual dom in-place diff. This has the side-effect of triggering the onupdate hook, rather than oninit/oncreate. However, it's relatively common for a developer to want to synchronize the recreation of the component to the route change event.