gpt4 book ai didi

javascript - react : Child Component Does Not Rerender When Submitting Form

转载 作者:行者123 更新时间:2023-12-02 23:58:52 25 4
gpt4 key购买 nike

我是 React 新手,我将非常感谢任何帮助。我正在使用 create-react-app、react-router-dom 和express 服务器。当我尝试向博客文章(称为“详细信息”的子组件)提交评论时,它会存储在数据库中,但是该组件似乎没有更新,并且我看不到新评论。因此,我可以看到仅在我刷新页面后而不是在表单提交后才发表新评论。我想我没有正确设置 componentDidUpdate,但我不知道如何做到这一点,所以我可以立即看到评论。

这是我的 App.js:

class App extends Component {
constructor(props) {
super(props)
this.state = {
userId: null,
username: null,
isAdmin: false,
isAuthed: false,
jwtoken: null,
posts: [],
filtered: [],
}
this.handleSubmit = this.handleSubmit.bind(this)
}

static authService = new AuthService();
static postService = new PostService();
static commentService = new CommentService();

componentDidMount() {

const isAdmin = localStorage.getItem('isAdmin') === "true"
const isAuthed = !!localStorage.getItem('username');

if (isAuthed) {
this.setState({
userId: localStorage.getItem('userId'),
username: localStorage.getItem('username'),
isAdmin,
isAuthed,
})
}
this.getPosts()

}

componentDidUpdate(prevProps, prevState, posts) {
if (prevState === this.state) {
this.getPosts()
}
}


handleChange(e, data) {
this.setState({
[e.target.name]: e.target.value
})
}

handleCommentSubmit(e, data) {

e.preventDefault();
e.target.reset();
App.commentService.createComment(data)
.then(body => {
this.getposts()
if (!body.errors) {
toast.success(body.message);
}
else {
toast.error(body.message);
}
}
)
.catch(error => console.error(error));

}

getPosts() {
App.postService.getPost()
.then(data => {
this.setState({
posts: data.posts.length? data.posts : []
});
}
)
.catch(e => this.setState({ e }))
}

render() {

return (
<Fragment>
<Header username={this.state.username} isAdmin={this.state.isAdmin} isAuthed={this.state.isAuthed} logout={this.logout.bind(this)} />

<Switch>

<Route exact path="/" render={(props) => (
<Home
posts={this.state.posts}
handleSearchSubmit={this.handleSearchSubmit.bind(this)}
handleChange={this.handleSearchChange.bind(this)}
{...props} />
)} />

<Route path="/posts/:id" render={(props) =>
<Details handleSubmit={this.handleCommentSubmit.bind(this)}
isAdmin={this.state.isAdmin}
isAuthed={this.state.isAuthed}
posts={this.state.posts}
handleChange={this.handleChange}
{...props} />} />



</Switch>

<Footer posts={this.state.posts} formatDate={this.formatDate} />
</Fragment>
);
}
}

export default withRouter(App);

这是我的Details.js:

class Details extends Component {
constructor(props) {
super(props);
this.state = {
post: null,
comment: null
}
this.handleChange = props.handleChange.bind(this);
}

componentDidMount() {
const { posts, match } = this.props;

this.setState({
post: posts.length
? posts.find(p => p._id === match.params.id)
: null,
userId: localStorage.getItem('userId')
})
}

componentDidUpdate(prevProps) {
const { posts, match, isAuthed } = this.props;

if (JSON.stringify(prevProps) === JSON.stringify(this.props)) {
return;
}

this.setState({
post: posts.length
? posts.find(p => p._id === match.params.id)
: null
});
}

render() {
const { post } = this.state;
const { isAdmin, isAuthed } = this.props;

if (!post) {
return <span>Loading post ...</span>;
}

return (
<section className="site-section py-lg">

<form onSubmit={(e)=> this.props.handleSubmit(e, this.state)} className="p-5 bg-light">

<div className="form-group">
<label htmlFor="message">Message</label>
<textarea name="comment" id="message" onChange={this.handleChange} cols={30} rows={10} className="form-control" defaultValue={ ""} />
</div>
<div className="form-group">
<input type="submit" defaultValue="Post Comment" className="btn btn-primary" />
</div>
</form>}
</section>
);
}
}

export default Details;

任何帮助将不胜感激!

最佳答案

你正在犯一个任何新的 React 开发人员都会犯的错误。只要记住一件事:-

UI is a function of state

因此,只有当您的状态更新时,您的 UI 才会更新。

提交评论后,不要再次获取您的所有评论,只需concat您的新评论到当前状态,提交成功后您就会看到您的评论

关于javascript - react : Child Component Does Not Rerender When Submitting Form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55257621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com