简体   繁体   English

在渲染道具功能中使用反应钩子

[英]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.

相关问题 如何使用 React Hooks 在 map function 内动态和有条件地渲染 select 选项 - How to dynamically and conditionally render select options inside of a map function using React Hooks (React-Select 挂钩)如何使用 Select 的 onChange 渲染道具更新 state? - (React-Select hooks) How can I update state using Select's onChange render prop? React Hooks:传递 state 道具不是 function? - React Hooks: Passing state prop is NOT a function? 如果 React Native Function 中的 prop 更改,则渲染 - Render if prop changes in React Native Function React hooks:回调作为 prop 在调用时根据它重新渲染每个钩子 - React hooks: callback as prop re-render every hooks depending on it when it's called 使用映射函数中的反应挂钩为变量赋值 - assign values to variables using react hooks inside map function React w/hooks:防止使用函数作为道具重新渲染组件 - React w/hooks: prevent re-rendering component with a function as prop 在 HOC 中使用 useState/Hooks 导致错误“Hooks can only be called inside of a function component” - React Using useState/Hooks In HOC Causes Error "Hooks can only be called inside of the body of a function component" 发送prop,然后将其用作React中的函数? - Sending prop and then using it as a function in React? 反应: Map Function 内的儿童道具 - React: Child Prop inside Map Function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM