添加钩子组件时渲染的钩子比上次渲染时更多
Rendered more hooks than during the previous render when adding a hook component
我有一个 useInput 挂钩组件,其工作方式如下:
useInput(
<input placeholder="phone number" />,
"phone"
)
它得到一个 (input,inputName) 和 returns 一个挂钩的输入组件。
当我想动态更改现有输入在我的视图中的可见性时,出现错误:渲染的钩子比上一次渲染时多。
{this.state.showMyInput && useInput(
<input placeholder="phone number" />,
"phone"
)
}
从 react documentation 开始,您不能将挂钩与条件运算符一起使用。
您可以一直调用 hook 并将结果存储在变量中,然后只调节渲染。
const input = useInput(input, inputName);
...
{this.state.showMyInput && input}
根据 React 文档,您不应在条件语句中调用挂钩。相反,在你的钩子中使用条件:As explained here
我的问题是我在代码的 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
上方,这解决了我的问题
我有一个 useInput 挂钩组件,其工作方式如下:
useInput(
<input placeholder="phone number" />,
"phone"
)
它得到一个 (input,inputName) 和 returns 一个挂钩的输入组件。 当我想动态更改现有输入在我的视图中的可见性时,出现错误:渲染的钩子比上一次渲染时多。
{this.state.showMyInput && useInput(
<input placeholder="phone number" />,
"phone"
)
}
从 react documentation 开始,您不能将挂钩与条件运算符一起使用。
您可以一直调用 hook 并将结果存储在变量中,然后只调节渲染。
const input = useInput(input, inputName);
...
{this.state.showMyInput && input}
根据 React 文档,您不应在条件语句中调用挂钩。相反,在你的钩子中使用条件:As explained here
我的问题是我在代码的 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
上方,这解决了我的问题