正在更新状态在UI中不能正确反映
问题描述:
我正在研究一个应用程序,允许用户在页面上发布消息并将其显示。应用程序将帖子从最新到最旧。我遇到的问题是,如果例如在页面上有十个帖子,顶部一个被喜欢,然后创建一个新的帖子 - 新的帖子被添加到页面的顶部,并且来自以前的最高职位转到新的职位(默认情况下应该有零个喜欢) - 错误地在页面上呈现喜欢。正在更新状态在UI中不能正确反映
请注意,帖子和喜欢在服务器端正确更新,并且状态正确更新以反映这些更改,但状态和用户界面不同步,因为它们应该在执行onSubmit()
方法后执行CreatePostForm组件。
还有其他人遇到过类似的问题吗?我很感激有关如何解决的任何建议。
PostsPage.js
class PostsPage extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
user: this.props.auth.user,
location: "main"
};
this.loadPosts = this.loadPosts.bind(this);
this.loadPosts();
};
loadPosts() {
this.props.loadPostsRequest(this.state).then(
(results) => {
console.log(results.data.posts);
this.setState({
posts: results.data.posts
});
});
}
render() {
const { createPostRequest } = this.props;
const posts = this.state.posts.map((post, i) =>
<Post
loadPostsRequest={loadPostsRequest}
key={i}
postId={post.postId}
userId={this.state.user.userId}
content={post.postBody}
/>
);
return (
<div className="container-fluid" id="posts-container">
<div className="row">
<div className="col-md-4 col-md-offset-4 posts-wrapper">
<div id="create-post-form">
<CreatePostForm
createPostRequest={createPostRequest}
history={this.props.history}
loadPosts={this.loadPosts}
/>
</div>
{ posts }
</div>
</div>
</div>
);
}
}
CreatePostForm.js
export class CreatePostForm extends React.Component {
constructor(props) {
super(props);
this.state = {
postBody : "",
user: this.props.auth.user
};
this.onSubmit = this.onSubmit.bind(this);
this.onChange = this.onChange.bind(this);
}
onChange(e) {
this.setState({
[e.target.name] : e.target.value
});
}
onSubmit(e) {
e.preventDefault();
this.props.createPostRequest(this.state).then(
() => {
this.props.loadPosts();
})
}
render() {
return (
<div className="create-post-inner col-md-12">
<form id="createPost" onSubmit={ this.onSubmit } >
<textarea value={this.state.postBody} className="form-control postInput" name="postBody" onChange={ this.onChange } placeholder="Write something on this page..." >
</textarea>
<input type="submit" className="submit btn btn-primary" />
</form>
</div>
);
}
}
答
不要在帖子中的地图使用index
为key
。当一个新帖子出现时,新帖子与前一篇文章的key
相同,因此React将其视为相同的元素。假设postId
对于每篇文章都是唯一的,请改用它。
请发表一个答案,然后参考。 – Sachith
你完全正确的@azium,这是诀窍:)有一种感觉,这是微不足道的,谢谢你! – AnchovyLegend
@Sachith什么?我不明白你的评论。 – azium