我有一个包含对象数组的状态,我想在 for 循环内更新我的对象。 这是我的代码: 每个对象都包含值、文本和时间。 time 应在 for 循环内更新。
const [initialValues, setInitialValue] = useState([
{
value: 128,
text: '128 Kb',
time: ''
},
{
value: 256,
text: '256 Kb',
time: ''
},
{
value: 512,
text: '512 Kb',
time: ''
},
{
value: 750,
text: '750 Kb',
time: ''
},
{
value: 1024,
text: '1 MB',
time: ''
},
{
value: 2048,
text: '2 MB',
time: ''
},
{
value: 3072,
text: '3 MB',
time: ''
},
{
value: 4096,
text: '4 MB',
time: ''
},
{
value: 5120,
text: '5 MB',
time: ''
}
]);
我想要更新状态的 for 循环: 计算是一个将在用户端的 onPress 事件上调用的函数。
const [number, setNumber] = useState('1')
const [data, setData] = useState('1024')
const calculate = () => {
if (number) {
let size = number * data * 8
size = percentage(12, size) + size;
for (let value of initialValues) {
let data = value.value;
data = (size / data).toFixed();
// here is my approach but not correct
setInitialValue({ ...initialValues, time: data })
}
}
}
但是结果是不确定的。
你应该将你的计算函数更改为此
const calculate = () => {
if (number) {
let size = number * data * 8;
size = percentage(12, size) + size;
const newValues = [...initialValues.slice()];
for (let i = 0; i < newValues.length; i++) {
let data = (size / data).toFixed();
newValues[i].time = data;
}
setInitialValue(newValues);
}
}
1- 使用map更新特定元素:
const [array, setArray] = useState([...]); // Initialize your state array
const updateElement = (index, newValue) => {
setArray(array.map((item, i) => (i === index ? newValue : item)));
};
2- 使用展开运算符和切片创建副本并更新元素:
const [array, setArray] = useState([...]); // Initialize your state array
const updateElement = (index, newValue) => {
const newArray = [...array]; // Create a copy of the original array
newArray[index] = newValue; // Update the specific element
setArray(newArray); // Set the state with the updated array
};
3- 使用 Array.prototype.slice 和 Array.prototype.concat 创建副本并更新元素:
const [array, setArray] = useState([...]); // Initialize your state array
const updateElement = (index, newValue) => {
const newArray = array.slice(); // Create a copy of the original array
newArray[index] = newValue; // Update the specific element
setArray(newArray); // Set the state with the updated array
};
将初始值存储在变量中并将其传递给 useState,如下所示
const [initialValues, setInitialValue] = useState(initialVaule);
const [number, setNumber] = useState(1)
const [data, setData] = useState(1024)
const calculate = () => {
if (number && data) {
let size = number * data * 8
size = percentage(12, size) + size;
let updatedValue = intialValues.map( item => {
return item.time = (size / data).toFixed();
})
setInitialValue(updatedValue);
}
}