javascript - Reactjs - Changing JSON based on state -


solved: solution on bottom

i have drop down menu changes current state of component. this:

<select onchange={event => this.setstate({typeoflist: event.target.value})}>   <option value="list.a">list a</option>   <option value="list.b">list b</option> </select> 

the problem when set state throws me error click on item in menu. because have function changes json use list. here snippet of code:

json

const list = require("./list.json") 

list.json huge, looks this:

{     "a":{         "objects":{             "term":["ball"],             "image":["./img/ball"]         }     },     "b":{         "objects":{             "term":["stick"],             "image":["./img/stick"]         }     }, } 

state

constructor(props){ super(props)          this.state={             term:'',             typeoflist: list.a         }     } 

function throws error

createarr(){     let item = this.state.typeoflist.split(/(\s)/)     let arr = []     for(var i=0;i<item.length;i++){         if(/(\[(.*?)\]|\((.*?)\))/g.test(item[i])){             arr.push(item[i])         }         (var key in this.state.typeoflist){             for(var j=0;j<this.state.typeoflist[key].term.length;j++){                 if (this.state.typeoflist[key].term[j] === item[i]){                     arr.push(item[i])                 }             }         }     }     return arr } 

the console says "typeerror: cannot read property 'length' of undefined". function works until click list change state. i'm not sure if practice. how should changing list in json?

solution: called json object wrong way. did assign typeoflist string this:

constructor(props){   super(props)    this.state={     term:'',     typeoflist: "a"   } } 

and called using [this.state.typeoflist] instead of typing this.state.typeoflist. can keys typing list[this.state.typeoflist][key]

"typeerror: cannot read property 'length' of undefined" because have set value of this.state.typeoflist[key] string. thus, this.state.typeoflist[key].term becomes undefined.

onchange={event => this.setstate({typeoflist: event.target.value})}

event.target.value string

i'm guessing need update value of term instead


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -