我正在映射多个单选按钮(组)选项,并且当用户单击单选按钮时,想要向数组添加选定的值和uniqueIds。
使用当前代码,我可以获得当前单击的值,但无法添加到数组中。
{result !== null && result.length > 0 ? (
<div>
{result.map(item => {
const label = item.question
const listOptions = item.options.map(item => {
return (
<Radio
name={item.uniqueId}
inline
value={item.uniqueId}
key={item.uniqueId}
className="radio-options"
checked={item.checked}
onChange={e => {
this.handleChange(label, uniqueId);
}}
>
{item.options}
</Radio>
);
});
return (
<div className="radio-options-overview">
<p>{label}</p>
{listOptions}
</div>
);
})}
handleChange = (label, uniqueId) => {
console.log(label, uniqueId);
let addToArray = [];
this.setState({ selectedItems: addToArray})
};
数组看起来像这样,
[
{ "label": "ageRange", "uniquId": 2 },
{ "label": "smoker", "uniquId": 1 },
{ "label": "exOption", "uniquId": 3 }
]
答案 0 :(得分:1)
您快到了。 @Clarity提供了很好的解决方案。 如果您想替换现有值并用新值替换
尝试一下
handleChange = (label, uniqueId) => {
const { selectedItems } = this.state
// Find items that already exists in array
const findExistingItem = selectedItems.find((item) => {
return item.uniqueId === uniqueId;
})
if(findExistingItem) {
// Remove found Item
selectedItems.splice(findExistingItem);
// set the state with new values/object
this.setState(state => ({
selectedItems: [...state.selectedItems, {
label, uniqueId
}]
}))
} else {
// if new Item is being added
this.setState(state => ({
selectedItems: [...state.selectedItems, {
label, uniqueId
}]
}))
}
};
答案 1 :(得分:0)
您可以这样做:
handleChange = (label, uniqueId) => {
this.setState(state => ({ selectedItems: [...state.selectedItems, uniqueId]}));
};
使用数组展开和setState
的函数形式,请确保您不直接改变状态并将项目添加到最新状态。
如果要添加一对label: uniqueId
对对象,可以这样做:
handleChange = (label, uniqueId) => {
this.setState(state => ({
selectedItems: [...state.selectedItems, {
[label]: uniqueId
}]
}));
};
编辑:如果要覆盖具有相同标签的项目,最简单的方法是将它们存储为一个对象而不是一个数组,因此具有相同标签的项目将覆盖现有的项目:
handleChange = (label, uniqueId) => {
this.setState(state => {
return { selectedItems: { ...state.selectedItems, [label]: uniqueId } };
});
};
答案 2 :(得分:-1)
老实说,我不知道您要做什么,但是如果您需要在数组内添加对象(或其他东西),则可以使用.push()
方法。例如:
let addToArray = [];
let test = {"label": "ageRange", "uniquId": 2};
addToArray.push(test);
console.log(addToArray); //[{label: "ageRange", uniquId: 2}]