[英]ReactJS - how to structure components to refresh a block with data?
我開始玩React,並嘗試構建一個簡單的應用程序,在其中有一個帖子列表,並在添加新帖子后將該帖子添加到列表中。 這是我到目前為止的內容:
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import Moment from 'react-moment';
import LoadModal from './LoadModal';
import NewPost from './NewPost';
class Posts extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
loading: true
};
}
componentDidMount() {
axios.get('/posts')
.then(response => {
this.setState({ posts: response.data, loading: false });
});
}
toggleItem(index) {
console.log('clicked index: '+index);
this.setState({
activeKey: this.state.activeKey === index ? null : index
})
}
moreLess(index) {
if (this.state.activeKey === index) {
return (
<span>
<i className='fas fa-angle-up'></i> Less
</span>
);
} else {
return (
<span>
<i className='fas fa-angle-down'></i> More
</span>
);
}
}
render () {
let content;
if (this.state.loading) {
content = 'Loading...';
} else {
content = this.state.posts.map(post => {
return(
<li key={post.id}>
<div>
<span>{post.id}</span>
<i className="fas fa-clock"></i>
<Moment format="MMM DD @ HH:MM">
<span className="badge badge-pill badge-primary">{post.created_at}</span>
</Moment>
<button className="btn btn-primary btn-xs" style={{'marginLeft': '10px'}} onClick={this.toggleItem.bind(this, post.id)}>
{this.moreLess(post.id)}
</button>
</div>
<div className={this.state.activeKey === post.id ? "msg show" : "msg hide"}>{post.message}</div>
</li>
)
});
}
return (
<div>
<h1>Posts!</h1>
<div className="row">
<NewPost />
</div>
<div className="row">
<div className="col-md-6">
<ul>
{content}
</ul>
</div>
<div className="col-md-6">
<div>
Modal
</div>
</div>
</div>
</div>
);
}
}
export default Posts
和
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
class NewPost extends React.Component {
constructor(props) {
super(props);
this.state = {
namee: '',
description: ''
}
this.handleChangeNamee = this.handleChangeNamee.bind(this);
this.handleChangeDescr = this.handleChangeDescr.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChangeNamee(event) {
this.setState({
namee: event.target.value
});
}
handleChangeDescr(event) {
this.setState({
description: event.target.value
});
}
handleSubmit(event) {
event.preventDefault();
const form_data = {
namee: this.state.namee,
description: this.state.description
};
axios.post('/posts/testtt', { form_data })
.then(res => {
console.log(res);
console.log(res.data); // here, I can see added the new post along with the old ones. How is that possible?
Posts.setState({ posts: response.data, loading: false });
})
}
render () {
return (
<div style={{'marginBottom': '20px'}}>
<form onSubmit={this.handleSubmit}>
<input name='namee' value={this.state.namee} onChange={this.handleChangeNamee} />
<input name='description' value={this.state.description} onChange={this.handleChangeDescr} />
<button onClick={this.handleItem}>Submit</button>
</form>
</div>
);
}
}
export default NewPost
我將帖子添加到Rails后端的數據庫中:
def testtt
Post.create(message: params[:form_data][:description])
@posts = Post.order('created_at')
render json: @posts
end
我苦苦掙扎的是-我向數據庫中添加了一個新帖子,但是-如何將該新帖子添加到現有帖子列表中?
編輯:還添加了我的index.html.erb (它僅在此處呈現組件)。
<%= react_component('Header', {title: 'Radek'}) %>
<%= react_component("HelloWorld", { greeting: "Hello" }) %>
<%= react_component("LoadModal") %>
<%= react_component("Posts") %>
首先,我覺得在創建后退還所有帖子是過度工程的感覺。 因此,讓我們做類似的事情:
@post = Post.new(params.require(:post).permit(:message))
if post.save
render json: @post
else
render json: @post.errors, status: :unprocessable_entity
end
在前端嘗試類似
handleSubmit(event) {
event.preventDefault();
const form_data = {
namee: this.state.namee,
description: this.state.description
};
axios.post('/posts/testtt', { form_data })
.then(res => {
console.log(res);
console.log(res.data);
this.props.onAddPost(res.data)
})
}
在NewPost中,請記住給它一個onAddPost
的道具,例如<NewPost onAddPost={(e) => this.addPost(post, e)}/>
, addPost
定義addPost
如下所示:
addPost(post){
const oldPosts = this.state.posts;
this.setState({posts: oldPosts.push(post)})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.