在反应中拼接一个数组不断删除第一个元素
Splice an array in react keeps removing the first element
在我的待办事项应用程序上工作时,当我想从数组中删除一个元素时,它一直在删除第一个元素...
我找不到原因。
有什么想法吗?我复制了链接到我的删除功能的代码位!
谢谢!
function App () {
const [activities, setActivities] = useState([]);
const [color, setColor] = useState ('Black');
const [complete, setComplete] = useState([]);
//ADD NEW ACTIVITY
/* activities*/
function addActivity (data) {
let newActivity = { data, done:false, isMotivating: false, id: sum , color: 'Black' }
sum++;
setActivities((activities) => [ ...activities, newActivity])
//console.log(`App: ${JSON.stringify(data)}`)
};
function toggleColor (a) {
setColor ('')
activities[a.id].isMotivating = activities[a.id].isMotivating ? false : true
if (activities[a.id].isMotivating === false) {
setColor ('green')
activities[a.id].color = color
} else {
setColor ('red')
activities[a.id].color = color
}
console.log(activities[a.id])
return activities;
}
function removeTodo (id ) {
const newTodos = [...activities];
newTodos.splice(id, 1);
setActivities(newTodos);
};
}
你的 sum
似乎是通过 let/var
声明的,它将在每次重新渲染时初始化为 0,因此你的每个 id
可能都设置为 0。
您可以像这样使用 useRef
:-
const uuid = useRef(0);
里面addActivity
function addActivity (data) {
let newActivity = { data, done:false, isMotivating: false, id:uuid.current , color: 'Black' }
uuid.current++;
setActivities((activities) => [ ...activities, newActivity])
//console.log(`App: ${JSON.stringify(data)}`)
};
但不确定使用 id
作为 index
拼接是否是最好的方式,因为您总是在删除内容,数组长度会改变。
在我的待办事项应用程序上工作时,当我想从数组中删除一个元素时,它一直在删除第一个元素... 我找不到原因。
有什么想法吗?我复制了链接到我的删除功能的代码位!
谢谢!
function App () {
const [activities, setActivities] = useState([]);
const [color, setColor] = useState ('Black');
const [complete, setComplete] = useState([]);
//ADD NEW ACTIVITY
/* activities*/
function addActivity (data) {
let newActivity = { data, done:false, isMotivating: false, id: sum , color: 'Black' }
sum++;
setActivities((activities) => [ ...activities, newActivity])
//console.log(`App: ${JSON.stringify(data)}`)
};
function toggleColor (a) {
setColor ('')
activities[a.id].isMotivating = activities[a.id].isMotivating ? false : true
if (activities[a.id].isMotivating === false) {
setColor ('green')
activities[a.id].color = color
} else {
setColor ('red')
activities[a.id].color = color
}
console.log(activities[a.id])
return activities;
}
function removeTodo (id ) {
const newTodos = [...activities];
newTodos.splice(id, 1);
setActivities(newTodos);
};
}
你的 sum
似乎是通过 let/var
声明的,它将在每次重新渲染时初始化为 0,因此你的每个 id
可能都设置为 0。
您可以像这样使用 useRef
:-
const uuid = useRef(0);
里面addActivity
function addActivity (data) {
let newActivity = { data, done:false, isMotivating: false, id:uuid.current , color: 'Black' }
uuid.current++;
setActivities((activities) => [ ...activities, newActivity])
//console.log(`App: ${JSON.stringify(data)}`)
};
但不确定使用 id
作为 index
拼接是否是最好的方式,因为您总是在删除内容,数组长度会改变。