I tried to make state object array as below
class DescriptionComponent extends React.Component {
constructor(props) {
super(props);
var initial_object={};
initial_object['type']={}
for(var i=0;i<20;i++){
if(i===0){
initial_object['type'][i]="Building";
}
else if(i===1){
initial_object['type'][i]="Storage";
}
else if(i===2){
initial_object['type'][i]="Building size";
}
else{
initial_object['type'][i]="Component";
}
this.setState(initial_object);
}
}
The render function
render()
{
return (
//clonable elements
<ul className="description-input">
{Array(20).fill(1).map((el, i) =>
<li >
<select name="type" onChange={this.setValue.bind(this, 'type',i)}>
<option value="Component">Component</option>
<option value="Building">Bulding</option>
<option value="Storage">Storage</option>
<option value="Building Size">Building size</option>
</select>
<div className={"int-input" +this.state.type[i]!='Building' ? 'hidden' :''}>
<input type="text" name="int_input" onChange={this.setValue.bind(this, 'int_input',i)}/>
</div>
</li>
)}
</ul>
);
I am trying to predefine the states so that I can pre load some form element with default values .
I got error Uncaught TypeError: Cannot read property 'type' of null
I want to declare something like below which is giving syntax error as well
this.state={
type[0]:'Building',
type[1]:'Building',
type[2]:'Building',
type[3]:'Building',
type[4]:'Building',
type[5]:'Building',
type[6]:'Building',
type[7]:'Building',
type[8]:'Building',
type[9]:'Building',
}
In the constructor, you should set the state directly instead of calling setState
:
this.state = {};
So it would be:
class DescriptionComponent extends React.Component {
constructor(props) {
super(props);
initial_object['type'] = {};
for (var i = 0; i < 20; i++) {
if (i === 0) {
initial_object['type'][i] = 'Building';
} else if (i === 1) {
initial_object['type'][i] = 'Storage';
} else if (i === 2) {
initial_object['type'][i] = 'Building size';
} else {
initial_object['type'][i] = 'Component';
}
}
this.state = initial_object;
}
}
The error is saying that this.state
is undefined
If you want to set it directly, then you would write it as an array:
this.state = {
type: [
'Building',
'Storage',
'Building size',
'Component',
'Component',
'Component' // etc..
]
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.