简体   繁体   中英

Optional parameter in Arrow Function

I have a handler like

handleSelect = (k0, k1, v) => {
    ...
    }
};

And I want to make k1 here optional. Is there a good way?

There is no good way. This isn't specific to React or arrows.

A variadic function with optional parameter in the middle requires to parse arguments:

handleSelect = (...args) => {
  let k0, k1, v;
  if (args.length > 2) {
    [k0, k1, v0] = args;
  } else {
    [k0, v0] = args;
    k1 = 'default';
  }
  ...
};

This may result in obscure API. A better recipe for a function with several parameters some of which can be optional is to accept an object with options. A function doesn't depend on parameter order this way:

handleSelect = ({ k0, k1 = 'default', v }) => {
  ...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM