首页 > 解决方案 > 如何解决函数中的参数问题?

问题描述

我有一个功能,我在多个组件中使用。它从组件收集数据并将其存储在数据库中。我的问题是函数有很多参数,其中一些可能不会在某些组件中使用。看一看 :

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 未定义”。你能建议我如何解决这个问题吗

标签: javascriptreactjsvue.js

解决方案


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
  };
  ...
}

推荐阅读