简体   繁体   English

我正在尝试设置 reactjs State 动态值

[英]I am trying to set reactjs State dynamic value

I have defined an array which contains state properties.我已经定义了一个包含 state 属性的数组。 I am checking each state property by looping through array if its empty then picking the current iteration item and getting the state value through this iteration variable but it give undefined ie this.state.item is undefined and setting pass_msg state property accordingly?My state is I am checking each state property by looping through array if its empty then picking the current iteration item and getting the state value through this iteration variable but it give undefined ie this.state.item is undefined and setting pass_msg state property accordingly?My state is

 this.state={
    old_pass:'',
    conf_pass:'',
    new_pass:'',
    pass_msg:''
}

update_password=(e)=>{
    let checks=["old_pass","new_pass","conf_pass"];
    checks.forEach(item=>{
    // give value  
    console.log('item',item)
    // but this is undefined .problem is here
    console.log('item',this.state.item)
    if(this.state.item === ''){
      this.setState({pass_msg:item+"is required"});
      return;
    }
})

} }

The reason this.state.item is undefined is because the state does not have a property item. this.state.item 未定义的原因是因为 state 没有属性项。 If you want to use a variable as a key to get the property from the state, you will need to get it like this:如果要使用变量作为键从 state 中获取属性,则需要这样获取:

this.state[item]

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

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