动态<svelte:component>道具的反应性

时间:2019-10-07 00:35:38

标签: svelte

我的问题与此previous one (do-dynamic-props-exist-in-svelte-3)类似。我按照建议使用传播道具,但似乎不起作用。

上下文:我正在用Svelte和我的状态机库编写Conduit RealWorld应用程序。每个路线都有一个组件,每个组件都有自己的一组道具。所以我使用如下:

RealWorld.svelte

<script>
  import Home from "./Home.svelte"
  import { routes } from "../constants"

  // Props
  // Common props
  export let dispatch;
  export let user;
  export let route;
  // Home route props
  export let tags;
  export let articles;
  export let page;
  export let activeFeed;
  export let selectedTag;
  export let favoriteStatus;

  const { home, signUp } = routes;

  // Component which will be displayed depending on the route
  const componentRoutes= {
    [home]: Home,
    // [signUp]: Signup
  };
  // Props for the component which will be displayed
  const componentRoutesProps={
    [home]: () => ({tags, articles, page, activeFeed, selectedTag, favoriteStatus})
  };

  $: component = componentRoutes[route]
  $: componentProps = componentRoutesProps[route]()
  $: commonProps = {dispatch, user, route}
  $: console.info(`Realworld`, component.name, componentProps, commonProps, {tags, articles, page, activeFeed, selectedTag, favoriteStatus})
</script>

<svelte:component this="{component}" {...componentProps} {...commonProps} />

但是,使用前面的代码会导致反应性降低,这意味着道具确实发生了变化,但是RealWorld组件没有更新。

与以下代码相同:

<svelte:component this="{component}" {tags} {articles} {page} {activeFeed} {selectedTag} {favoriteStatus} {dispatch} {user} {route} />

工作正常。

我认为这可能是由于引用的更改所致,斯维尔特对传递的引用做出了反应,这些引用后来在销毁过程中以某种方式丢失了?那你怎么使用传播道具呢?我该如何处理用例?

我总是可以使用更简单的if/then/else构造,但是我想知道是否有更优雅的方法。

1 个答案:

答案 0 :(得分:0)

这里没有Svelte错误。问题是我忘记在$:之前添加componentProps使其具有反应性:

  // Props for the component which will be displayed
+  $: componentRoutesProps={
+    [home]: {tags, articles, page, activeFeed, selectedTag, favoriteStatus}
  };

  $: component = componentRoutes[route]
  $: componentProps = componentRoutesProps[route]
  $: commonProps = {dispatch, user, route}
  $: console.info(`Realworld`, component.name, componentProps, commonProps, {tags, articles, page, activeFeed, selectedTag, favoriteStatus})