【问题标题】:Incorrect value is returned when retrieving value from a Store从 Store 检索值时返回不正确的值
【发布时间】:2019-09-24 04:20:42
【问题描述】:

我有一个显示一组按钮的组件:

Step navigator component

对于按钮中的每一次点击,我都想显示一个不同的视图并将当前视图设置为一个“步骤”变量。由于我不想从应用程序中的不同组件访问此变量,因此我将此“步骤”变量存储在存储中。

我正在从渲染列表时设置的数据属性中检索值:

StepNavigator.svelte

<script>
  import { step } from "../stores/step.js";
  import { onMount } from "svelte";
  import Icon from "./Icon.svelte";

  function setStep(e) {
    step.update(n => e.target.tabIndex);
  }

  let stepItems = [
    {
      title: "Option 1",
      selections: []
    },
    {
      title: "Option 2",
      selections: ["One selection"]
    },
    {
      title: "Option 3",
      selections: []
    },
    {
      title: "Option 4",
      selections: ["Selection 1", "Selection 2"]
    },
    {
      title: "Option 5",
      selections: []
    },
    {
      title: "Option 6",
      selections: []
    }
  ];
</script>
<section class="step-navigator">
  <h2>Configure product item 1</h2>
  <p>Lorem ispum dolor samet dolor ipsum lorem samet.</p>
  <ul>
    {#each stepItems as stepItem, index}
      <li>
        <button class={$step === index ? 'active' : 'inactive'} on:click={setStep} tabindex={index}>
          <div>
            <h3>{stepItem.title}</h3>
            <div class="selected-items">
              {#if stepItem.selections.length > 0}
                {#each stepItem.selections as selection, index}
                  {#if index !== 0}, {selection}{:else}{selection}{/if}
                {/each}
              {:else}Nothing selected{/if}
            </div>
          </div>
          <Icon iconType="ok" iconColor={stepItem.selections.length > 0 ? 'var(--theme-color--success)' : '#999'} strokeWidth="4" />
        </button>
      </li>
    {/each}
  </ul>
  <div class="price-container">
    <div class="price">7560 USD</div>
    <div class="price-information">Disclaimer text goes here</div>
  </div>
</section>

Step.js

import { writable } from 'svelte/store';

export const step = writable(0); 

问题是我在单击按钮时随机获得值“-1”:

GIF showing the error when clicking the buttons

为什么会这样?我在这里做错了什么?

【问题讨论】:

  • step.update(n => e.target.tabIndex);吗???或者先调试你的 setStep 函数
  • 如果您能详细说明您的答案,那将非常有帮助。

标签: javascript svelte


【解决方案1】:

我同意您的标签索引返回为 -1 很奇怪,即使您似乎设置正确。

但我可能不使用setStep 中的tabIndex,而是直接传递索引,如下所示:

function setStep(index) {
  step.update(n => index);
}
<button class={$step === index ? 'active' : 'inactive'} on:click={() => setStep(index)} tabindex={index}>

这是一个 Svelte REPL:https://svelte.dev/repl/b70ed5be24074cf48c3d3e6a375c327e?version=3.12.1


旁注,但如果您没有使用 n 变量,那么使用 set 而不是 update 可能会更简洁:

function setStep(index) {
  step.set(index);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2016-10-09
    • 2021-10-26
    • 2015-10-13
    • 2014-12-06
    • 2021-02-01
    • 2017-08-21
    相关资源
    最近更新 更多