arrays - 从数组列表中将对象推送到数组
问题描述
我正在尝试将 ojbects 推送到数组列表中的特定数组中。我能够推送 ojbect,但它会在根目录中创建额外的数组。
const [variants, setVariants] = useState([]);
const colorNameRef = useRef('');
const sizeNameRef = useRef('');
const sizeSkuRef = useRef('');
const addEntryClick = (e) => {
e.preventDefault();
const newEntry = {
colorName: colorNameRef.current.value,
id: e.timeStamp.toFixed(0),
sizes: []
};
setVariants((preEntry) => [...preEntry, newEntry]);
};
const handleAddSize = (index) => (e) => {
e.preventDefault();
console.log(index);
let newSize = {
name: sizeNameRef.current.value,
id: sizeSkuRef.current.value
};
setVariants([...variants, variants[index].sizes.push(newSize)]);
};
function handleSubmit() {
console.log(variants);
}
return(
<>
<div>
<input type="text" ref={colorNameRef} />
<button onClick={addEntryClick}>Add</button>
</div>
<div>
{variants &&
variants.map((variant, index) => (
<div key={index}>
<div className={variant.id}>{variant.id}</div>
<div>{variant.colorName}</div>
<div className="ftw=semi" data-id={variant.id}>
<div>
<input type="text" ref={sizeNameRef} />
<input type="text" ref={sizeSkuRef} />
</div>
<button className="btn-blue" onClick={handleAddSize(index)}>
Add
</button>
</div>
{/* {variant.sizes &&
variant.sizes.map((size, index) => (
<div key={index}>{size.name}</div>
))} */}
</div>
))}
</div>
<button onClick={handleSubmit}>Submit</button>
</>
)
我正在寻找的理想结果是
[
{colorName : 'something', id: '234234', sizes : [{}]
{colorName : 'something', id: '234234', sizes : [{}]
{colorName : 'something', id: '234234', sizes : [{}]
]
addEntryClick() 创建一个 ojbect,其中包含颜色名称、id 和空数组大小,handleAddSize() 查找数组索引并将 ojbect 推送到 siezes
到目前为止,当我运行此代码时,我能够完全按照我的意愿进行操作,但是当我单击 hadnleAddSize() 时,它会创建一些添加数组
[
{colorName : 'something', id: '234234', sizes : [{name: 'new', id:'2342']
1 <-- this is created everytime I click on handleAddSize()
]
解决方案
似乎您想修改一个数组项,但是如果您使用推送,您将修改原始数组(使用反应状态时不应该这样做),并且推送结果是一个指示数组新的数字长度,这就是为什么您要向大小数组添加一个数字。
如果你想修改数组而不改变它,有多种方法可以做到,这里是其中一种。
const handleAddSize = (index) => (e) => {
e.preventDefault();
console.log(index);
const newSize = {
name: sizeNameRef.current.value,
id: sizeSkuRef.current.value
};
// Returns a new modified array.
const newModifiedArr = variants.map((item, currentIndex) => {
// If the index matches with the current index
if (currentIndex === index) {
// Returns a new object with the sizes property modified to add your newSize object
return {
...item,
sizes: [...item.sizes, newSize]
}
}
// if the index does not match return the current item without modifying it.
return item
})
// Set the state with the new generated array
setVariants([...newModifiedArr]);
};
推荐阅读
- c# - 如何在 C# 中使用 MVC 模式处理事件
- slack - 将 Slack 交互式消息菜单分组为一个表单
- c# - Swagger 2.0 - 用于操作错误的模棱两可的 HTTP 方法
- python - 错误:需要整数参数,得到浮点数
- php - 使用 PHP 和 MYSQL 重定向到客户页面
- java - spring data elasticsearch 7类未找到异常
- javascript - 如何在 C# 中增加 maxJsonLength?
- c - 检查文件是否存在后更改 fopen 模式的正确方法是什么?
- node.js - 无法从反应组件中的道具读取属性
- git - git结帐
vs git checkout 分支