使用动态变量获取状态值React Native

时间:2019-03-08 20:58:38

标签: javascript react-native

因此,在初始状态下,我有多个对象从EV1-EV15编号,如何在循环中获取数据?像这样:

    for (var i = 0; i < 15; i++) {
        percentage = (0.5 / this.state.EVi.timeToFull) * 100;
        newSOC = Math.round((this.state.EVi.soc + percentage) * 10) / 10;
        if (newSOC >= 100) {
            newSOC =  100;
        }
        array.push(newSOC);
    }

1 个答案:

答案 0 :(得分:0)

this.state.EViEVi中专门寻找名为this.state的属性。取而代之的是,将索引插入一个字符串中,并使用该字符串从状态中获取适当的值。

for (var i = 0; i < 15; i++) {
    const currentItem = `EV${i}`;
    percentage = (0.5 / this.state[currentItem].timeToFull) * 100;
    newSOC = Math.round((this.state[currentItem].soc + percentage) * 10) / 10;
    if (newSOC >= 100) {
        newSOC =  100;
    }
    array.push(newSOC);
}