javascript - 如何解决函数中的参数问题?
问题描述
我有一个功能,我在多个组件中使用。它从组件收集数据并将其存储在数据库中。我的问题是函数有很多参数,其中一些可能不会在某些组件中使用。看一看 :
export default async function addUserLogs(account, service, terminal,isSaved,isSentToGateway,amount ) {
const obj = {
serviceID: service,
terminalID: terminal,
amountName: account,
amount: amount,
isSaved: isSaved,
isSentToGateway: isSentToGateway,
};
const db = await InitDb();
const tx = db.transaction('userLogs', 'readwrite');
const store = tx.objectStore('userLogs');
const index = await store.put(obj);
let params = {};
if (window.localStorage.getItem('params') !== null) {
params = JSON.parse(window.localStorage.getItem('params'));
}
window.localStorage.setItem(
'params',
JSON.stringify({ ...params, userLogIndex: index })
);
}
例如,我在一个组件上传递给函数的帐户和服务参数,不需要其他参数。在另一个组件中,我只需要传递数量参数,但我需要指定以前的参数以不覆盖其他值。但出现错误“帐户、服务、终端、isSaved、isSentToGateway 未定义”。你能建议我如何解决这个问题吗
解决方案
addUserLogs 可以接收带有可选键的对象,并将最后收到的对象与新的对象合并:
export default async function addUserLogs(newParams) {
const lastParams = <get the last params from storage>;
const obj = Object.assign(lastParams, newParams);
...
}
// usage examples
addUserLogs({amountName: 'x', serviceID: 1, terminalID: 2, isSaved: true ,isSentToGateway: false, amount: 10});
addUserLogs({isSentToGateway: false, amount: 10});
addUserLogs({amountName: 'x', serviceID: 1, terminalID: 2});
如果您想对 addUserLogs 签名更具声明性,您可以做一些链接:
export default async function addUserLogs({amountName, serviceID, terminalID, isSaved ,isSentToGateway, amount}) {
const lastParams = <get the last params from storage>;
const newParams = {
amountName: amountName || lastParams.amountName,
serviceID: serviceID || lastParams.serviceID,
terminalID: terminalID || lastParams.terminalID,
isSaved: isSaved === undefined ? lastParams.isSaved : isSaved,
isSentToGateway: isSentToGateway === undefined ? lastParams.isSentToGateway : isSentToGateway,
amount: amount === undefined ? lastParams.amount : amount
};
...
}
推荐阅读
- jquery - angularjs如何像jQuery一样设置ajax
- c# - Xamarin.Forms (IOS):在应用关闭之前处理一些数据的最佳实践
- powershell - TFS 版本定义 - 未使用自定义帐户详细信息创建应用程序池
- git - TortoiseHg/Mercurial <=> TortoiseGit <=> TortoiseSvn/Subversion 快速比较
- jquery - 在 Angular 6 CLI 项目中使用 jQuery 脚本
- ios - 如何解决 Xcode 10 beta 中的错误“链接器命令失败,退出代码 1(使用 -v 查看调用)”?
- asp.net-mvc - MSBuild web 包没有额外的文件/目录结构
- c# - 如何计算开始坐标和结束坐标之间的坐标 - uwp c#
- visual-studio-code - vscode中的Mypy构建任务失败
- react-native - React Native 样式覆盖数组