我正在构建一个组件,该组件记录针对某个活动和该活动的任务输入的时间。
“删除”按钮(左侧的X)无法正常工作,该按钮将从数组'weekPanels中删除该按钮所属的单个weekPanel组件。 当前,它会删除被单击的面板,但也也会删除以下所有面板。
我在这里有一个演示:https://jscomplete.com/playground/s409549
组件状态:
const [weekId, setWeekId] = useState(100);
const [weekPanels, setWeekPanels] = useState([]);
const [monday, setMonday] = useState(0);
const [tuesday, setTuesday] = useState(0);
const [wednesday, setWednesday] = useState(0);
const [thursday, setThursday] = useState(0);
const [friday, setFriday] = useState(0);
const [saturday, setSaturday] = useState(0);
const [sunday, setSunday] = useState(0);
“添加活动/任务”按钮将WeekPanel组件添加到weekPanels状态。然后更新weekId。
const addWeekPanel = () => {
setWeekPanels(weekPanels.concat(
<WeekPanel
key={weekId}
weekId={weekId}
weekPanels={weekPanels}
activitiesList={props.activitiesList}
tasksList={props.tasksList}
monday={monday}
tuesday={tuesday}
wednesday={wednesday}
thursday={thursday}
friday={friday}
saturday={saturday}
sunday={sunday}
handleHoursChange={handleHoursChange}
handleWeekPanelDelete={handleWeekPanelDelete}
activityTask={{}}
/>));
setWeekId(weekId + 1);
}
足够完成这项工作。
这是删除功能:(删除记录)
const handleWeekPanelDelete = deleteId => {
const newWeekPanels = weekPanels.filter(week => week !== deleteId);
setWeekPanels(newWeekPanels);
}
它也有一个奇怪的交互作用,即在到达weekPanels.filter()之前,console.log在不同点退出状态,日志记录显示了删除的结果。
答案 0 :(得分:0)
尝试使用splice,它会在删除项目后返回数组(从指定的索引中删除一个元素)
callback(null, {
type: 'TheType',
isPattern: false,
id: 'EntityID',
attributes: [
{
name: 'lumniscence',
type: 'Integer',
value: '432'
}
]
});
或使用您的exisitng代码,使用filter的此变体(我指定数组中正在处理的当前元素的索引)。
const handleWeekPanelDelete = deleteId => {
weekPanels.splice(deleteId, 1);
setWeekPanels(weekPanels);
}