简体   繁体   English

反应如何在循环中记录不同的 state 元素

[英]React How to log different state elements in a loop

I'm trying to loop through 2 of the key value pairs in my state.我正在尝试遍历 state 中的 2 个键值对。 They both have very similar names the only difference between them is that one ends in Day and the other ends in Night.他们都有非常相似的名字,唯一的区别是一个在白天结束,另一个在晚上结束。 Here is a simplified example of my project right now.这是我现在项目的简化示例。 My objective is for the log to come out with the results shown below:我的目标是让日志得到如下所示的结果:

state = {
        energyType: "Electricity",
        meterRate: "oneRate",
        firstEnergyAmountDay: 1,
        firstEnergyAmountNight: 2,
    }

let days

if (this.state.energyType === "Electricity" && this.state.meterRate === "twoRate") {
            days = ["Day", "Night"]
        } else {
            days = ["Day"]
        }

        days.map(day => {
            console.log(this.state.firstEnergyAmount + day);
        })

Right now my log just returns:现在我的日志刚刚返回:

undefinedDay未定义日

undefinedNight未定义的夜晚

And I want the log to give me:我希望日志给我:

1 1

2 2

To do a computed property of an object, you need to use square brackets and a string要执行 object 的计算属性,您需要使用方括号和字符串

console.log(this.state["firstEnergyAmount" + day])

So that will concatenate strings together to produce either "firstEnergyAmountDay" or "firstEnergyAmountNight" , and then the square brackets will look up the property with that key.因此,这会将字符串连接在一起以生成"firstEnergyAmountDay""firstEnergyAmountNight" ,然后方括号将使用该键查找属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM