我正在使用React.js制作一个列表。此应用程序将包含两个列表,用户可以创建包含一些项目的列表。
例如,
1)清单清单(例如1)水果清单2)蔬菜清单)
2)项目清单(例如1)水果 - 1 Apple,[2] Banana,[3] Orange)
列表数据存储为数组,项目列表存储在对象数组中。我无法弄清楚的是将数组传递给状态中的对象。
这是我的代码: App.js
class App extends Component {
constructor() {
super();
this.state = {
lists: [], // this holds the name of each list
items: {} // this property names of this object are the names of the lists; their values are arrays of the items in each list
};
}
handleAddList(list) {
let lists = this.state.lists;
lists.push(list);
let item = [lists] // how can I pass array to object??
this.setState({
lists: lists,
items: item
})
console.log(this.state)
}
handleAddItem(item) {
let items = this.state.items;
items.push(item);
this.setState({
items
})
}
render() {
return (
<div className="App">
<AddList addList={this.handleAddList.bind(this)} />
<div id="listsDiv" className="List">
<Lists lists={this.state.lists} items={this.state.items} addItem={this.handleAddItem.bind(this)} />
</div>
</div>
);
}
}
AddList.js
class AddList extends Component {
constructor(){
super();
this.state = {
newList : {}
}
}
handleSubmit(e) {
e.preventDefault(); // this prevents the page from reloading -- do not delete this line!
if(this.refs.id.value ===''){
alert('Add list')
} else {
this.setState({
lists: this.refs.id.value
}, function(){
this.props.addList(this.state.lists);
});
}
}
render() {
return (
<div id="addListDiv">
<form onSubmit={this.handleSubmit.bind(this)}>
<div id='addList'>
<label>What will be on your next list?
<input type='text' ref='id' id='newID'></input>
</label>
</div><br />
<input type='submit' value='Create List' />
</form>
</div>
);
}
}
答案 0 :(得分:0)
如果这是一个列表,则应将其初始化为空数组[]
。
此外,如果这是一个列表列表(如您所说),可能只将它们保留在一个状态支柱中,其中每个key
映射到特定的list
类型。
this.state = {
lists: {
fruits: ['apple', 'banana', 'orange'],
vegetables: ['tomato', 'carrot', ...],
}
}
因此,每次向任何列表添加新项目时,状态操作都会变得更容易:
addItem(type, item) {
this.setState({
lists: {
...this.state.lists,
[type]: [
...this.state.lists[type],
item,
]
}
})
}