简体   繁体   中英

Can you pass parameters to a React hook that takes in no parameters?

I am working on a certain assessment where I have to modify a code base to implement a feature. Now, there is a jsx file that calls a hook, and a js file in which the hook is defined. Let's call the jsx file thing.jsx, and let's say that it has some lines of code that look like this:

import useHook from '../hooks/useHook';
const thing = useHook({thingy1, thingy2, thingy3});
//rest of code goes here

Then, the file in which the hook is defined (useHook.js) looks like this:

function useHook() {
  //I'm supposed to implement this function
}

export default useHook;

Now, notice that in the hook's definition, there are no parameters. Yet, in the jsx file, they pass in an object.

Since this is an assessment for me, there are certain things that they don't want me to change. I'm torn as to whether or not they are expecting me to leave the function definition with no parameters in it as shown above (which would imply that you can just simply pass in parameters to hooks that have no parameters in their definitions?), or if they are actually looking for me to add the parameters myself.

What do you think? Can you just pass parameters to a parameter-less hook in another file, or am I right to just add the parameters to the function myself?

React Hooks is javascript functions, and if you want to access the parameters of function you must use inside the hook, like this:

 function useHook({thing1, thing2, thing3}) { //I'm supposed to implement this function }

Well, nothing wrong with passing parameters to a function that isn't expecting any. But it's just almost pointless. Since this is essentially javascript, it will definitely allow you to pass the params.

So, to answer your questions,

Can you just pass parameters to a parameter-less hook in another file,

Yes, you can.

or am I right to just add the parameters to the function myself?

This depends on your requirement. It needs to be noted that formal parameters aren't the only way to access a function's parameters, it is futile to do so if the function does nothing with its arguments even after you pass them in.

Also, a small note for you, just in case it may help, do check out the arguments object. You could pass in the parameters, even without the function explicitly expecting them in the definition, and still use the parameters. Run the snippet below and see for yourself:

 function testFunc() { console.log(arguments[0]); console.log(arguments[1]); console.log(arguments[2]); } testFunc(1, 2, 3);

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