首页 > 解决方案 > 返回最后一个值而不是正确的值

问题描述

我想要的是每个名称都会获得它的关联值,但是下面的代码将打印每个循环上的所有值,然后它会在最后一个值处停止。

主页.html

<template>
   <div repeat.for="name of names">
    ${getValue(name)}
    <p>Hello ${value}</p>
   </div>
</template>

主页.js

export class Home {
    names = ["one", "two", "three"];

    constructor() {
        this.getValue();
        this.value = "";
    }

    getData() {
        return httpClient.fetch('example.com/api/v')
            .then(response => response.json())
            .then(data => {
                return data;
            });
    }

    getValue(name) {
        this.getData()
            .then(data => this.value = data.name);
    }
}

实际结果:

Hello value3 //It prints value1 value2 then stops at value3
Hello value3 //It prints value1 value2 then stops at value3
Hello value3 //It prints value1 value2 then stops at value3

预期成绩:

Hello value1
Hello value2
Hello value3

标签: javascriptaurelia

解决方案


推荐阅读