我有两个功能,用于向端点添加/删除数据。我目前有两个功能,一个是添加数据,另一个是删除数据。
const addMultipleAuthorities = async () => {
const postMultipleAuthoritiesData = {
sid: selectedPerson,
authorities: selectedAuth,
action: 'add'
}
console.log(postMultipleAuthoritiesData);
}
const removeMultipleAuthorities = async () => {
const removeMultipleAuthoritiesData = {
sId: selectedPerson,
authorities: selectedAuth,
action: 'remove'
}
console.log(removeMultipleAuthoritiesData)
}
这两个按钮都在单独的按钮上调用。...我想知道如何通过一个函数来编写此代码,因为我似乎正在重复自己的atm。
这是调用函数的两个按钮
<Button
text='Add Authorities'
className='Button Dark Main'
onClick={addMultipleAuthorities}
/>
<Button
text='Remove Authorities'
className='Button Dark Main'
onClick={removeMultipleAuthorities}
/>
答案 0 :(得分:1)
一种可能是烦人的(某些性能在他们的答案中具有)
另一种可能性是在处理程序中使用的按钮上设置属性:
在此,我使用data attribute(任何data- *属性),因为它们非常适合此类事情。
const clickHandler = async (e) => {
const action = e.target.dataset.action;
const removeMultipleAuthoritiesData = {
sId: selectedPerson,
authorities: selectedAuth,
action
}
console.log(removeMultipleAuthoritiesData)
}
<Button
text='Add Authorities'
className='Button Dark Main'
data-action="add"
onClick={clickHandler}
/>
<Button
text='Remove Authorities'
className='Button Dark Main'
data-action="remove"
onClick={clickHandler}
/>
答案 1 :(得分:0)
您可以创建一个函数,给定action
,该函数返回记录该对象的函数:
const makeClickHandler = action => () => {
const data = {
sid: selectedPerson,
authorities: selectedAuth,
action,
};
console.log(data);
};
<Button
text='Add Authorities'
className='Button Dark Main'
onClick={makeClickHandler('add')}
/>
<Button
text='Remove Authorities'
className='Button Dark Main'
onClick={makeClickHandler('remove')}
/>