[英]How to pass an argument in useCallback hook?
I'm trying to use the useCallback
hook, to change the language using gatsby-intl
plugin, they have a method ( changeLocale()
) what can be used to change the default language of the site.我正在尝试使用useCallback
钩子,使用gatsby-intl
插件更改语言,他们有一个方法( changeLocale()
)可用于更改站点的默认语言。 I wanted to avoid passing props in JSX arrow's functions despite the solution is working so I'm trying to use the useCallback
hook.尽管解决方案有效,但我想避免在 JSX 箭头的函数中传递道具,所以我尝试使用useCallback
钩子。
onClick={()=>switchLanguage(language.iso)}
Here's my component:这是我的组件:
import React, { useCallback, useState } from 'react';
import { changeLocale } from 'gatsby-plugin-intl';
import { useLanguages } from '../../../hooks/useLanguages';
export const LanguageSwitcher = (callback, deps) => {
const languages = useLanguages();
const switchLanguage = useCallback(language => changeLocale(language),[]);
return <ul>
{languages.map((language, index) => <li key={index} onClick={switchLanguage(language.iso)}>{language.name}</li>)}
</ul>;
};
The code above creates an infinite rendering, the code is entering on switchLanguage
function without clicking it.上面的代码创建了一个无限渲染,代码是在没有点击它的情况下进入switchLanguage
函数。
However, if I remove the argument, it works as expected but I don't know what language is the user clicking.但是,如果我删除该参数,它会按预期工作,但我不知道用户单击的是什么语言。
const switchLanguage = useCallback(()=> console.log('item clicked'),[]);
I've also tried to use other hooks such as useState
but it creates too many renders.我也尝试使用其他钩子,例如useState
但它创建了太多的渲染。
How can I pass an argument to the useCallback
?如何将参数传递给useCallback
? If it is not possible, which will be the best workaround or approach?如果不可能,那将是最好的解决方法或方法?
onClick={switchLanguage(language.iso)}
calls switchLanguage
and sets its return value as onClick
, just like onClick = switchLanguage(language.iso)
would outside JSX. onClick={switchLanguage(language.iso)}
调用switchLanguage
并将其返回值设置为onClick
,就像onClick = switchLanguage(language.iso)
在 JSX 之外一样。
To bind the argument to it, you'd use a wrapper function:要将参数绑定到它,您可以使用包装函数:
onClick={() => switchLanguage(language.iso)}
...or bind
, though it also creates a function: ...或bind
,尽管它也创建了一个函数:
onClick={switchLanguage.bind(null, language.iso)}
But : There's probably not much to be gained by using useCallback
in your example.但是:在您的示例中使用useCallback
可能没有什么useCallback
。 That being the case, you probably don't need switchLanguage
at all:既然如此,您可能根本不需要switchLanguage
:
import React, { useCallback, useState } from 'react';
import { changeLocale } from 'gatsby-plugin-intl';
import { useLanguages } from '../../../hooks/useLanguages';
export const LanguageSwitcher = (callback, deps) => {
const languages = useLanguages();
return <ul>
{languages.map((language, index) => <li key={index} onClick={() => changeLocale(language.iso)}>{language.name}</li>)}
</ul>;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.