2

I try to do this:

 getInitialState: function(){
    return({
        people: [] .... or people: [{id: "", key: ""}] or people: [[id: ][key: ]]
    });
},

so I have an id and a key every person and I want to store it like this.

4
  • What is the problem here ? Commented Feb 25, 2017 at 19:07
  • error issue in the declaration Commented Feb 25, 2017 at 19:16
  • I saw the declaration... What is the relationship between React and two dimensional array ? Commented Feb 25, 2017 at 19:17
  • i have a function with a query, and then i would like to push this two elements(id, key) to the array. Commented Feb 25, 2017 at 19:21

1 Answer 1

3

Looks like a syntax error. Try:

getInitialState () { 
  return {
    people: []
  }; 
}

This creates an empty array in your initial state. You can just populate your people array normally like so:

let p = this.state.people.slice();
p.push({id: "", key: ""});
this.setState({people: p});

The first line creates a copy of your people. You then push a new item to the temporary array. Finally you replace the old people state with the new one.

A one-liner way of doing this:

this.setState({people: this.state.people.concat([{id: "", key: ""}])});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but I can't push the two values to the array
@Zimzo. Do you want the values in the initial state or after the component has mounted?
After the component has mounted @Chris

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.