Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在编写将项添加到状态为的不同数组的函数时遇到问题_Javascript_Reactjs_React Native - Fatal编程技术网

Javascript 在编写将项添加到状态为的不同数组的函数时遇到问题

Javascript 在编写将项添加到状态为的不同数组的函数时遇到问题,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我正在尝试创建一个函数,允许我将项目添加到 本地状态中的数组。我可以创建几个函数 这迎合了该州的每个阵营,但我觉得 应该只需要一个函数就可以做到这一点。我现在的样子 这样做是行不通的。我可能需要退一步,重新考虑一下 但我希望能找到一些方法让这一切顺利进行 谢谢 this.state = { category1: [], category2: [] } addItem(category, type){ this.setState({ category: [...this.st

我正在尝试创建一个函数,允许我将项目添加到 本地状态中的数组。我可以创建几个函数 这迎合了该州的每个阵营,但我觉得 应该只需要一个函数就可以做到这一点。我现在的样子 这样做是行不通的。我可能需要退一步,重新考虑一下 但我希望能找到一些方法让这一切顺利进行

谢谢

this.state = {
  category1: [],
  category2: []
}

addItem(category, type){
  this.setState({
    category: [...this.state.category, type]
  })
}

listsOfItems.types.map((type, i) => (
  <ListItem 
    onPress={ () => this.addItem(category1, type)}
  />
))

listOfOtherItems.types.map((type, i) => {
  <ListItem
    onPress={ () => this.addItem(category2, type)}
  />
})
this.state={
类别1:[],
类别2:[]
}
附加项(类别、类型){
这是我的国家({
类别:[…this.state.category,type]
})
}
listsOfItems.types.map((type,i)=>(
this.addItem(category1,type)}
/>
))
列表OtherItems.types.map((类型,i)=>{
this.addItem(category2,type)}
/>
})

我不认为这种情况下的重复有那么糟糕,但是如果你真的想推广它,你可以使用:

this.state={
类别1:[],
类别2:[]
}
附加项(类别、类型){
这是我的国家({
[类别]:[…此.状态[类别],类型]
})
}
listsOfItems.types.map((type,i)=>(
this.addItem('category1',type)}
/>
))
列表OtherItems.types.map((类型,i)=>{
this.addItem('category2',type)}
/>
})

漂亮!感谢您的帮助:D@Dres令人惊叹的!没问题
this.state = {
  category1: [],
  category2: []
}

addItem(category, type){
  this.setState({
    [category]: [...this.state[category], type]
  })
}

listsOfItems.types.map((type, i) => (
  <ListItem 
    onPress={ () => this.addItem('category1', type)}
  />
))

listOfOtherItems.types.map((type, i) => {
  <ListItem
    onPress={ () => this.addItem('category2', type)}
  />
})