我正在React中创建一个Comment组件,并将Add Comment表单作为子组件。注释组件具有hasNewComment
状态,该状态由子项“添加注释”表单通过作为道具传递的回调函数handleNewComment
成功更新。我可以看到状态在子窗体中提交时已更新(render()下的console.log显示hasNewComment
切换为true),但是注释列表未刷新。我的印象是任何状态更改都会触发重新渲染。
这是使用create-react-app创建的。我曾尝试将子组件移到父组件中,但结果相同。
//PARENT
class Comments extends React.Component {
state = {
hasComments: !this.props.comments.length,
hasNewComment: false
}
handleNewComment = () => {
// STATE CHANGE UPON FORM SUBMIT IN CHILD
this.setState({
hasNewComment: true
})
}
render() {
console.log(this.state)
const {comments} = this.props
const {hasComments, hasNewComment} = this.state
return (
<section className="comments">
<h3>Comments</h3>
{(hasComments || hasNewComment) ? (
// list of comments working fine
) : (
// no comments
)}
// USING THIS LINE TO PASS DOWN CALLBACK
<CommentForm newComment={this.handleNewComment} />
</section>
)
}
}
// CHILD
class CommentForm extends React.Component {
state={...} // nothing to do with the parent
handleSubmit = (e) => {
e.preventDefault()
let url = this.props.apiUrl
const { newComment } = this.state
fetch(`${url}/api/comments`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(newComment)
}).then(() => this.props.newComment()) // CALLBACK TO UPDATE PARENT STATE
}
render() {
return(
<form onSubmit={this.handleSubmit} className="comment-form">
...
</form>
)
}
}
我希望父注释中的注释列表在状态更改时重新呈现,但是即使状态更改成功,也不会发生任何事情。