javascript - 如何在数组中推送新对象?
问题描述
如何在数组中推送新对象?每当我在反应中运行此代码时,它都会不断替换数组中的第一个对象。
radioButtonVal = (e) => {
this.radioid = e.target.name;
this.radiovalue = e.target.value;
this.radioButtonValTitles = [];
this.radioButtonValFind = this.radioButtonValTitles.find(x => x.id === this.radioid);
if(this.radioButtonValFind){
this.radioButtonValFind.id = this.radioid;
this.radioButtonValFind.value = this.radiovalue;
} else {
this.radioButtonValTitles.push({id: this.radioid, value: this.radiovalue})
}
}
输出是 ({object, object}) 只是替换当前值
预期输出是 ({object, object}, {object, object}...)
解决方案
问题是每次调用函数时都分配一个空数组
radioButtonVal = (e) => {
this.radioid = e.target.name;
this.radiovalue = e.target.value;
this.radioButtonValTitles = []; //right here you initiate an empty array
this.radioButtonValFind = this.radioButtonValTitles.find(x => x.id === this.radioid);
if(this.radioButtonValFind){
this.radioButtonValFind.id = this.radioid;
this.radioButtonValFind.value = this.radiovalue;
} else {
this.radioButtonValTitles.push({id: this.radioid, value: this.radiovalue})
}
}
您应该做的是将 radioButtonValTitles 保持在您的状态,并在以后引用它们,如下所示:
constructor(props) {
super(props);
this.state = {
radioButtonValTitles: [],
};
}
然后像这样修改你的函数:
radioButtonVal = (e) => {
const { radioButtonValTitles } = this.state;
this.radioid = e.target.name;
this.radiovalue = e.target.value;
this.radioButtonValFind = radioButtonValTitles.find(x => x.id === this.radioid);
if(this.radioButtonValFind){
this.radioButtonValFind.id = this.radioid;
this.radioButtonValFind.value = this.radiovalue;
} else {
this.setState({
radioButtonValTitles: radioButtonValTitles.push({id: this.radioid, value: this.radiovalue})
)}
}
}
推荐阅读
- reactjs - 顺风CSS渐变问题
- linux - Bash:使用 bash 脚本抓取文本文件以查找电话号码
- javascript - 如何自动调用类中的函数
- ios - Getting an image-related exception when using a ListWheelScrollView in Flutter
- android - Android Kotlin - 在工具栏内设置徽标
- postgresql - 针对真实 postgres 数据库的 Spring Boot 集成测试
- swift - 存在方式通知何时将呈现自定义 UIView 或 removeFromSuperview()?
- dialogflow-cx - 使用 EventHandler 警告用户他们的会话即将结束
- php - Wordpress 404 在除主页外的所有页面上都找不到
- c++ - 从 arm-none-eabi 中排除标准库