如何解决ReactJS自定义钩子总是引发错误
React的新手,我探索了Custom Hooks,构建了一个简单的表单管理器:
首先,钩子(在components / hooks文件夹中):
import React,{useState} from 'react'
const useJalonForm = () => {
const [inputs,setInputs] = useState({})
// Handle form submission
const handleSubmit = (event) => {
if (event) {
event.preventDefault() // Don't really submit the form,let's handle by us
}
}
const handleInputChange = (event) => {
event.persist();
setInputs(inputs => ({...inputs,[event.target.name]: event.target.value}));
}
return {
handleSubmit,handleInputChange,inputs
}
}
export default useJalonForm
然后在一个组件中,我想使用这个钩子:
import React from 'react'
import useJalonForm from './hooks/useJalonForm'
const CreateJalon = () => {
// Hook destructuration to get every components
const { inputs,handleSubmit } = useJalonForm()
return (<form onSubmit={handleSubmit}>
<div className="form-group">
<label>Titre : </label>
<input type="text" name="title" required onChange={handleInputChange} value={inputs.title} />
</div>
<div className="form-group">
<select name="segment" size="1" onChange={handleInputChange} value={inputs.segment}>
<option value="">Sélectionner...</option>
<option value="state">State</option>
<option value="props">Props</option>
</select>
</div>
<div className="form-group">
<button type="submit">
Créer
</button>
</div>
</form>)
}
export default CreateJalon
从应用程序“装入”了表单组件:
import CreateJalon from './components/Jalon/CreateJalon'
// ...
render() {
const { jalons } = this.state
const jalonIteration = () => {
return jalons.map((jalon) => {
return <JalonComponent key={jalon.id} jalon={jalon} changeState={this.receiveJalon.bind(this)} />
})
}
const form = () => {
if (!jalons.length) {
return CreateJalon()
}
return null
}
return (
<div>
<ToolbarComponent jalons={jalons} />
{ form() }
{ jalonIteration() }
</div>
)
}
// ...
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This Could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
所以:
- 将类和函数混合在一起是一种实践吗?
- 为什么此消息
解决方法
请勿在循环,条件或嵌套函数中调用Hooks。
在您的情况下:
[12,45,67,89].each
#=> #<Enumerator: [12,89]:each>
[12,89].each { |num| num * 2 }
#=> [12,89]
并调用CreateJalon函数,将调用其挂钩。 因此您必须像下面那样修改代码:
if (!jalons.length) {
return CreateJalon()
}
当您使用 if (!jalons.length) {
return CreateJalon
}
时,最好也替换
form
具有:
{form()}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。