我的按钮和函数调用如下:
<td>
<button
id="home.js"
type="button"
className="btn btn-default btn-sm"
onClick={this._onButtonClickHome}
>
<span className="glyphicon glyphicon-plus" />
</button>
</td>
我的反应代码是:
constructor() {
this.state = {
idList: ["hi"],
showComponentHome: false
};
}
_onButtonClickHome(event) {
const idhome = event.target.id;
console.log(idhome);
this.state.idList.push(idhome);
console.log(this.state.idList);
this.setState({
showComponentHome: true
});
}
我无法将ID“home.js”添加到列表idList中。有人可以解决问题或建议更好的方法吗?谢谢。
<td><button id="home.js" type="button" className="btn btn-default btn-sm" onClick={(event) => this._onButtonClickHome(event)}><span className="glyphicon glyphicon-plus"></span></button></td>
_onButtonClickHome = (event) => {
// Your code
}
const { idList } = this.state;
[这相当于const idList = this.state.idList - 技术上称为对象解构]
idList.push("idhome");
你能尝试以下方法吗?
_onButtonClickHome(event) {
const idhome = event.target.id;
const idList = Object.assign([], this.state.idList);
idList.push(idhome);
this.setState({idList, showComponentHome: true});
}
问题可能是您使用this.state.idList
直接推送新元素,但这不是更新状态的好方法。您应该在状态中创建当前数组的副本,更新它,然后使用更新数组覆盖状态中的数组。
遵循其文档中定义的框架规则。更多阅读:doc部分:正确使用状态。有关不可变状态的观点。
这是工作解决方案,
import React, { Component } from "react";
class Solution extends Component {
state = {
idList: ["hi"],
showComponentHome: false
};
_onButtonClickHome = (idhome) => {
console.log(idhome);
let tempArr = [...this.state.idList, idhome];
this.setState({ idList: tempArr });
this.setState({
showComponentHome: true
});
console.log(tempArr);
}
render() {
return (
<button
type="button"
className="btn btn-default btn-sm"
onClick={() => this._onButtonClickHome("home.js")}
>
Set State
</button>
);
}
}
export default Solution;
我希望它有所帮助。