[英]Using react hooks inside render prop function
Taken from Rules of Hooks :取自钩子规则:
Don't call Hooks inside loops, conditions, or nested functions.
不要在循环、条件或嵌套函数中调用 Hook。 Instead, always use Hooks at the top level of your React function
相反,始终在 React 函数的顶层使用 Hooks
Given this recommendation by the react team, would using a hook at the top of a render props function be inadvisable?鉴于反应团队的这个建议,在渲染道具函数顶部使用钩子是否不可取? Assuming it depends on the value returned by the function.
假设它取决于函数返回的值。
const MyComponent = () => (
<RenderPropComponent>
{value => {
React.useEffect(() => {
// Magic
}, [value]);
return <p>Hello</p>;
}}
</RenderPropComponent>
);
I don't feel like it breaks their requirement我不觉得这违反了他们的要求
By following this rule, you ensure that Hooks are called in the same order each time a component renders
通过遵循此规则,您可以确保每次组件呈现时都以相同的顺序调用 Hook
But should I be doing the following instead?但是我应该做以下事情吗?
const MyComponent = ({ value }) => {
React.useEffect(() => {
// Magic
}, [value]);
return <p>Hello</p>;
};
const MyContainer = () => (
<RenderPropComponent>
{value => <MyComponent value={value} />}
</RenderPropComponent>
);
Hooks keep track of current rendering element.钩子跟踪当前的渲染元素。 And render prop function is not an element.
而渲染道具功能不是一个元素。 So you will hook into calling element and not into your prop function.
因此,您将挂钩调用元素而不是 prop 函数。 This render prop function will be treated as a custom hook.
此渲染道具功能将被视为自定义钩子。 You will get unexpected behavior if
RenderPropComponent
calls render prop function conditionally.如果
RenderPropComponent
有条件地调用 render prop 函数,你会得到意想不到的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.