【发布时间】:2021-01-22 00:51:59
【问题描述】:
我的代码基本上是一个带有文本输入和提交按钮的表单。每次用户输入数据时,我的代码都会将其添加到一个数组中并显示在表单下。
工作正常;但是,当我添加重复值时,它仍会将其添加到列表中。我希望我的代码计算这些重复项并将它们显示在每个输入旁边。 例如,如果我输入两个“Hello”和一个“Hi”,我希望我的结果是这样的: 2 你好 1 嗨
这是我的代码
import React from 'react';
import ShoppingItem from './ShoppingItem';
class ShoppingList extends React.Component {
constructor (props){
super(props);
this.state ={
shoppingCart: [],
newItem :'',
counter: 0 };
}
handleChange =(e) =>
{
this.setState ({newItem: e.target.value });
}
handleSubmit = (e) =>
{
e.preventDefault();
let newList;
let myItem ={
name: this.state.newItem,
id:Date.now()
}
if(!this.state.shoppingCart.includes(myItem.name))
{
newList = this.state.shoppingCart.concat(myItem);
}
if (this.state.newItem !=='')
{
this.setState(
{
shoppingCart: newList
}
);
}
this.state.newItem ="" ;
}
我的其余代码是这样的:
render(){
return(
<div className = "App">
<form onSubmit = {this.handleSubmit}>
<h6>Add New Item</h6>
<input type = "text" value = {this.state.newItem} onChange ={this.handleChange}/>
<button type = "submit">Add to Shopping list</button>
</form>
<ul>
{this.state.shoppingCart.map(item =>(
<ShoppingItem item={item} key={item.id} />
)
)}
</ul>
</div>
);
}
}
export default ShoppingList;
【问题讨论】:
-
render函数在哪里? -
您可以使用状态映射来存储字符串和计数(作为键值对),并且在 handleChange 上只需更新映射中值的计数
-
请分享你的
render函数。 -
我刚刚添加了包含地图和渲染的其余代码
标签: javascript arrays reactjs react-native