首页 > 解决方案 > 从 Store 检索值时返回不正确的值

问题描述

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

步骤导航器组件

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

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

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

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

标签: javascriptsvelte

解决方案


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

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

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);
}

推荐阅读