【发布时间】:2020-12-24 05:53:39
【问题描述】:
我想使用反应钩子将我的反应类组件转换为功能组件。它给出了如下错误。
Failed to compile
./src/templates/addPost.js
Line 6:29: React Hook "useState" is called in function "addPost" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
搜索关键字以了解有关每个错误的更多信息。 此错误发生在构建期间,无法消除。
我的代码是:
const AddPost = (props)=> {
const [post, setPost] = useState({
id: Math.random(),
title: '',
body: ''
})
const handleInput = (target, value) =>{
return {
id: post.id,
title: target.id == 'title' ? value : post.title,
body: target.id == 'body' ? value : post.body
}
}
const handleSubmit = (e)=>{
e.preventDefault()
console.log(post)
props.actionPost(post)
e.target.reset()
props.history.push('/post/'+ post.id)
}
return ( <form onSubmit={handleSubmit}>
<input onChange={(e)=>{setPost(handleInput(e.target, e.target.value))}} type="text" id='title'/>
<input onChange={(e) => { setPost(handleInput(e.target, e.target.value))}} type="text" id='body'/>
<button type="submit" onSubmit={handleSubmit}>Submit</button>
</form>)
}
const mapDispatchToProps = (dispatch) =>{
return {
actionPost: (post)=>{
dispatch(addPostAction(post))
}
}
}
export default connect(null, mapDispatchToProps)(AddPost)
【问题讨论】:
-
在 hooks 中,你不要使用 mapDispatchToProps ,这个视频可以帮助你将类组件更改为函数组件:youtube.com/watch?v=kLCTl1r_dUw
-
我使用带有钩子的 redux。但它已经解决了,我也可以将 mapDispatchToProps 与功能组件一起使用。
标签: javascript reactjs react-hooks