Ste*_*sen 6 reactjs eslint react-hooks
我创建了一个更高阶的组件,该组件应该为我的组件添加一些其他功能。但是,当我在该组件中使用react钩子时,会收到以下eslint警告。
无法在回调内部调用React Hook“ React.useEffect”。必须在React函数组件或自定义的React Hook函数中调用React Hooks。(反应钩/钩规则)
为什么会收到此警告?在HoC中使用挂钩是否被认为是不好的做法?
最小示例:
const Hello = props => <p>Greetings {props.name}</p>;
const Wrapper = Component => props => {
React.useEffect(() => {
// Do something here
}, []);
return <Component {...props} />;
};
export default Wrapper(Hello)
Run Code Online (Sandbox Code Playgroud)
codeandbox:https://codesandbox.io/s/proud-tree-5kscc
小智 13
转换
props => {
React.useEffect(() => {
// Do something here
}, []);
return <Component {...props} />;
};
Run Code Online (Sandbox Code Playgroud)
在您的 HOC 内部到一个函数(react-hooks/rules-of-hooks 正在抛出您在 HOC 返回的箭头函数中使用时显示的警告)
所以,把它改成
const Wrapper = Component =>
function Comp(props) {
React.useEffect(() => {
console.log("useEffect");
}, []);
return <Component {...props} />;
};
Run Code Online (Sandbox Code Playgroud)
并且效果被触发。
| 归档时间: |
|
| 查看次数: |
855 次 |
| 最近记录: |