我有一个非常简单的基本React应用程序,并且正在运行。我可以通过axios发布和获取数据,并且可以在控制台中看到,发布数据时,我的状态已更新,但是DOM无法反映出来,因此我需要刷新才能看到更改。请检查我做错了什么:
这是我在componentDidMount中的get方法:
componentWillMount() {
const { posts } = this.state;
axios
.get("dburl/posts.json")
.then(response => {
const data = Object.values(response.data);
this.setState({ posts : data });
});
}
这是我的表单细分的post方法。我正在创建带有标题和内容的帖子,并将其显示在屏幕中:
handleSubmit = event => {
event.preventDefault();
const {post} = this.state;
const {posts} = this.state;
axios
.post("dburl/posts.json", post)
.then(response => {
console.log(response);
const newPost = Object.values(response.data);
this.setState({ post: newPost });
const updatedPosts = posts.push({title:post.title,content:post.content});
console.log(post);
console.log(updatedPosts);
console.log(this.state.posts);
});
};
这是我显示数据的方式:
render() {
let posts = <p>No posts yet</p>;
if (this.state.posts !== null) {
posts = this.state.posts.map(post => {
return <Post key={post.id} {...post} />;
});
}
return (
<React.Fragment>
{posts}
<form className="new-post-form" onSubmit={this.handleSubmit}>
<label>
Post title
<input
className="title-input"
type="text"
name="title"
onChange={this.handleChange}
/>
</label>
<label>
Post content
<input
className="content-input"
type="text"
name="content"
onChange={this.handleChange}
/>
</label>
<input className="submit-button" type="submit" value="submit" />
</form>
</React.Fragment>
);
}
我不明白为什么它不更新DOM,而新帖子却没有立即显示。请检查。谢谢。
答案 0 :(得分:0)
您错误地更新了状态, 您的代码:
console.log(response);
const newPost = Object.values(response.data);
this.setState({ post: newPost });//this will update the state with new values
const updatedPosts = posts.push({title:post.title,content:post.content});//here you are
pushing the new values to the existing posts
console.log(post);
console.log(updatedPosts);
console.log(this.state.posts);
期望代码:
console.log(response);
const newPost = Object.values(response.data);
this.setState({ posts: [...this.state.posts, {title:post.title,content:post.content}]});
console.log(post);
console.log(this.state.posts);
这样,它将在更新posts数组后更新您的状态。