【问题标题】:Rendered more hooks than during the previous render when adding a hook component添加钩子组件时,比上一次渲染时渲染的钩子更多
【发布时间】:2019-10-02 06:04:28
【问题描述】:

我有一个 useInput 钩子组件,它的工作原理如下:

useInput(
    <input placeholder="phone number" />,
    "phone"
  )

它获取一个 (input,inputName) 并返回一个挂钩的输入组件。 当我想动态更改视图中现有输入的可见性时,我收到一个错误:Rendered more hooks than during the previous render.

{this.state.showMyInput && useInput(
        <input placeholder="phone number" />,
        "phone"
      )
}

【问题讨论】:

  • 您介意提供useInput 钩子的代码吗?
  • 组件顶部需要使用钩子

标签: reactjs react-hooks


【解决方案1】:

我的问题是我在代码的 return 语句之后使用了 useState 挂钩,例如:

function myComponenet () {
   if(loading) {return <Loading/>}

   const [myVar, setMyVar] = React.useState({})

   // my main component UI begins here

   <View>.....</View>
}

我不得不将这个const [myVar, setMyVar] = React.useState({}) 行移到if statement 上方,这解决了我的问题

【讨论】:

    【解决方案2】:

    react documentation 开始,您不能使用带有条件运算符的钩子。

    你可以一直调用 hook 并将结果存储在一个变量中,然后只调整渲染。

    const input = useInput(input, inputName);
    ...    
    {this.state.showMyInput && input}
    

    【讨论】:

    • 谢谢。这帮助我修复了我遇到的这个奇怪的错误。在有条件地执行的函数中创建了一个 useState 钩子。
    【解决方案3】:

    根据 react 文档,您不应在条件语句中调用钩子。相反,在你的钩子里使用条件:As explained here

    【讨论】:

      猜你喜欢
      • 2019-12-24
      • 1970-01-01
      • 2021-12-01
      • 2021-05-31
      • 2020-11-26
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 2021-10-12
      相关资源
      最近更新 更多