在 render prop 函数中使用 react hooks
Using react hooks inside render prop function
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function
根据 React 团队的建议,在渲染道具函数的顶部使用钩子是否不可取?假设它取决于函数返回的值。
const MyComponent = () => (
<RenderPropComponent>
{value => {
React.useEffect(() => {
// Magic
}, [value]);
return <p>Hello</p>;
}}
</RenderPropComponent>
);
我不觉得这违反了他们的要求
By following this rule, you ensure that Hooks are called in the same order each time a component renders
但我应该改为执行以下操作吗?
const MyComponent = ({ value }) => {
React.useEffect(() => {
// Magic
}, [value]);
return <p>Hello</p>;
};
const MyContainer = () => (
<RenderPropComponent>
{value => <MyComponent value={value} />}
</RenderPropComponent>
);
挂钩跟踪当前渲染元素。并且 render prop 函数不是一个元素。所以你将挂钩到调用元素而不是你的 prop 函数。此渲染道具功能将被视为自定义挂钩。如果 RenderPropComponent
有条件地调用 render prop 函数,你会得到意想不到的行为。
这并没有违反钩子的规则 - https://unsplash.com/blog/calling-react-hooks-conditionally-dynamically-using-render-props/#waitdoesntthisbreaktherulesofhooks
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function
根据 React 团队的建议,在渲染道具函数的顶部使用钩子是否不可取?假设它取决于函数返回的值。
const MyComponent = () => (
<RenderPropComponent>
{value => {
React.useEffect(() => {
// Magic
}, [value]);
return <p>Hello</p>;
}}
</RenderPropComponent>
);
我不觉得这违反了他们的要求
By following this rule, you ensure that Hooks are called in the same order each time a component renders
但我应该改为执行以下操作吗?
const MyComponent = ({ value }) => {
React.useEffect(() => {
// Magic
}, [value]);
return <p>Hello</p>;
};
const MyContainer = () => (
<RenderPropComponent>
{value => <MyComponent value={value} />}
</RenderPropComponent>
);
挂钩跟踪当前渲染元素。并且 render prop 函数不是一个元素。所以你将挂钩到调用元素而不是你的 prop 函数。此渲染道具功能将被视为自定义挂钩。如果 RenderPropComponent
有条件地调用 render prop 函数,你会得到意想不到的行为。
这并没有违反钩子的规则 - https://unsplash.com/blog/calling-react-hooks-conditionally-dynamically-using-render-props/#waitdoesntthisbreaktherulesofhooks