Проблема в том, что вы изменяете объекты состояния:
const onClickHandler = index => {
let oldPrimatLocations = primaryAdd;
let newPrimaryLocation = secondaryAdd[index];
let objIndex = secondaryAdd.findIndex(
obj => obj.value === oldPrimatLocations[0].value
);
secondaryAdd[objIndex + 1].label = oldPrimatLocations[0].label; // mutate state and mix up index
setPrimayAdd([newPrimaryLocation]);
setSecondaryAdd(secondaryAdd); // saved mutate state reference back in state
};
Решите: Если я правильно понимаю, если "primaryAdd1" находится в первичном массиве и пользователь нажимает на "desc3", тогда два значения меняются местами. Теперь «desc3» находится в первичном массиве, а «primaryAdd1» - во вторичном массиве с индексом 2.
primary: ["desc3"]
secondary: ["desc1", "desc2", "primaryAdd1", "desc4", "desc5", "desc6"]
Если пользователь теперь нажимает «desc6», он переставляется и теперь находится в первичном массиве, а «desc3» во вторичном массиве с индексом 5.
primary: ["desc6"]
secondary: ["desc1", "desc2", "primaryAdd1", "desc4", "desc5", "desc3"]
Решение: извлеките старые и новые объекты первичного расположения, поместите newPrimaryLocation в первичный массив и поместите oldPrimaryLocation во вторичный массив в тот же индекс
const onClickHandler = index => {
const oldPrimaryLocation = primaryAdd[0];
const newPrimaryLocation = secondaryAdd[index];
setPrimaryAdd([newPrimaryLocation]);
setSecondaryAdd(secondaryAdd =>
// functional update and map to return new array reference
secondaryAdd.map((el, i) => (i === index ? oldPrimaryLocation : el))
);
};
Различная реализация, чтобы сначала скопировать массивы, выполнить обмен и просто сохранить скопированные массивы в штат.
const onClickHandler = index => {
const primary = [...primaryAdd];
const secondary = [...secondaryAdd];
[secondary[index], primary[0]] = [primary[0], secondary[index]];
setPrimaryAdd(primary);
setSecondaryAdd(secondary);
};