我有一个小组件可以更改我网站的语言。由于 eslint 配置了 jsx-no-bind
,它会在下面的代码中引发错误。
const ChangeLanguage = ({ toggleLanguage }) => {
const toggle = () => {
console.log('hi')
toggleLanguage()
}
return (
<IconButton
onClick={toggle}
>
<Language /> // this is an svg-icon
</IconButton>
)
}
export default connect(null, { toggleLanguage })(ChangeLanguage)
我用谷歌搜索了 jsx-no-bind
用法。有人说我们应该启用它,因为在每次渲染时 javascript 都会生成新函数并且它会导致不必要的渲染(如 airbnb 代码约定 [link] )。但其他一些人表示它的性能改进可以忽略不计,并且会降低代码的可读性(例如 [link] )。这里有两个问题:
- 如何解决错误(即不禁用
jsx-no-bind
)。 - 你对
jsx-no-bind
配置有什么建议(即我是否应该从 eslint 配置中完全/部分删除它?)。
PS: 网上有更多关于将箭头函数或绑定(bind)方法作为 props 传递的文档。但我在问题陈述中只提到了其中两个。
最佳答案
此处记录了解决方案:https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md#react-hooks
Functional components are often used alongside hooks, and the most trivial case would occur if your callback is completely independent from your state. In this case, the solution is as simple as moving the callback out of your component:
const onClick = () => {
console.log("Independent callback");
};
const Button = () => {
return (
<button type="button" onClick={onClick}>Label</button>
);
};
Otherwise, the idiomatic way to avoid redefining callbacks on every render would be to memoize them using the
useCallback
hook:
const Button = () => {
const [text, setText] = useState("Before click");
const onClick = useCallback(() => {
setText("After click");
}, [setText]); // Array of dependencies for which the memoization should update
return (
<button type="button" onClick={onClick}>{text}</button>
);
};
关于javascript - 如何解决功能组件上的 jsx-no-bind 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55041956/