Код: Выделить всё
function MainScreen() {
const [stopwatches, setStopwatches] = useState([
new Stopwatch('A'),
new Stopwatch('B')
]);
const [selectedStopwatchIndex, setSelectedStopwatchIndex] = useState(-1);
let selectedStopwatch = selectedStopwatchIndex == -1
? null
: stopwatches[selectedStopwatchIndex];
return (
{
setStopwatches(s => {
const newArray = [...s];
newArray.splice(selectedStopwatchIndex, 1);
return newArray;
// return newArray.filter((_, i) => i !== selectedStopwatchIndex);
});
}}
/>
);
}
Код: Выделить всё
function StopwatchDetails({ stopwatch, removeStopwatch }) {
const [time, setTime] = useState('0:00:00');
useEffect(() => {
if (!stopwatch) return;
const interval = setInterval(() => {
setTime(stopwatch.getElapsedTimeFormatted());
}, 100);
return () => {
clearInterval(interval);
}
}, [stopwatch]);
return (
{stopwatch == null
? 'Info about the currently selected stopwatch will apear here!'
: `Time: ${time}`}
Remove
);
}
MainScreen включает StopwatchDetails. Когда я пытаюсь передать функцию удаления секундомера следующим образом:
Код: Выделить всё
removeStopwatch={() => {
setStopwatches(s => {
const newArray = [...s];
newArray.splice(selectedStopwatchIndex, 1);
return newArray;
});
}}
Однако, когда я пытаюсь передать функцию удаления секундомера следующим образом:
Код: Выделить всё
removeStopwatch={() => {
setStopwatches(s => {
const newArray = [...s];
return newArray.filter((_, i) => i !== selectedStopwatchIndex);
});
}}
Если я console.log значение selectedStopwatchIndex в стрелочной функции removeStopwatch, она правильно печатает индекс текущего выбранного секундомера.
Вот песочница кода, которая показывает эту проблему в файле MainScreen.jsx:
https://codesandbox.io/p/sandbox/recurs ... ier-ly4td9
Подробнее здесь: https://stackoverflow.com/questions/798 ... l-variable
Мобильная версия