我已将状态初始化为:
this.state = {
buildingNames: []
}
然后,我将新值添加到函数中的数组中:
onClickAddBuildingTextBoxHandler = (inputData) => {
this.setState({ buildingNames: [...this.state.buildingNames, inputData.value] });
}
因此,在我的渲染函数中,我将数组的值渲染为:
this.state.buildingNames.map((buildings, i) => {
return (
<div key={'building' + i}>
<div className={classes.sceBuildingNameContainer}>
<div className={classes.sceBenchmarkingBuildingName}>
{this.state.buildingNames} //its returning a single element
</div>
<button
className={classes.sceCloseIcon}
onClick={this.onClickDeleteBuildingIconHandler}>
<i className={"fas fa-times " + classes.sceBuildingCloseIcon} />
</button>
</div>
</div>
}
因此,当前正在发生的事情是,地图功能无法正常工作。我的意思是该块两次返回相同的值。当我添加一个新值时,它会附加到以前的状态。因此,如果我的图像再次添加新值,它将在 mnpq 之后附加。我想要的是一个接一个地添加新值。如何设置新状态对于那种情况?
答案 0 :(得分:2)
您正在使用map
遍历buildings
数组中的元素。回调函数中的第一个参数是当前元素,因此将其从复数buildings
更改为building
,然后在JSX {building}
中引用它。另外,不需要在密钥ID之前添加“ building”。
this.state.buildingNames.map((building, i) => {
return (
<div key={i}>
<div className={classes.sceBuildingNameContainer}>
<div className={classes.sceBenchmarkingBuildingName}>
{building}
</div>
</div>
</div>
);
}
答案 1 :(得分:0)
map function
的第一个参数是对正在循环的数组映射的当前元素的引用。
onClickAddBuildingTextBoxHandler = (inputData) => {
const tempState = [...this.state.buildingNames];
tempState.push(inputData.value);
this.setState({ buildingNames: tempState });
}
this.state.buildingNames.map((building, i) => {
return (
<div key={'building' + i}>
<div className={classes.sceBuildingNameContainer}>
<div className={classes.sceBenchmarkingBuildingName}>
{building} //Here you are refrencing the current element.
</div>
<button
className={classes.sceCloseIcon}
onClick={this.onClickDeleteBuildingIconHandler}>
<i className={"fas fa-times " + classes.sceBuildingCloseIcon} />
</button>
</div>
</div>
}