I have an object defined like this:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
lists: ["Dogs", "Cats"],
items: {Dogs:[], Cats:[]}
};
}
handleAddItem(item) {
console.log(item);
}
I have the variable
console.log(item);// output {Dogs:[{name: "lofi"}]}
I don't know how to verify which property is in the item
( Dogs
or Cats
) so that I can update the object items{} to make it becоme in my example like this:
items{Dogs:[{name: "lofi"}], Cats:[]}
When you add "lofi" to items.Dogs, you should do like this:
this.state.items.Dogs.push({name:'lofi'})
The console output shows that you made the Cats disappear, so I wondered that you override the items state like:
this.state.items = {Dogs:[{name:'lofi'}]}
If I guess wrong, please let me know.
Edit:
Pass the values as parameter is like below:
add category:
var new_category = 'Birds';
this.state.items[new_category] = [];
add item to category:
var category = 'Birds';
var new_item = 'dori';
this.state.items[category].push({name: new_item });
const item = {Dogs:[{name: "lofi"}]}
let whichAnimal = Object.keys(item)[0]; //Dogs
let animalObj = item[whichAnimal][0]; //{name:'lofi'}
this.setState({
items: this.state.items[whichAnimal].push(animalObj)
})
You can use Object.keys
to get all the keys and assuming your item
has only one variable at a time, we set with index 0. Storing it in a variable so that during setState
we will know which array in exact we going to push the item into
Since, this is a react app you want to use setstate
.
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
lists: ["Dogs", "Cats"],
items: {Dogs:[], Cats:[]}
};
}
handleAddItem(item) {
console.log(item);
var copy = JSON.parse(JSON.stringify(this.state.items));
copy["Dogs"].push({name: "lofi"}];
this.setState({items: copy});
}
}
In react don't try to change the state directly. Also, its always a best practice to copy the object first because if you change the original state object it can make your app behave unpredictable.
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.