简体   繁体   中英

ReactJS - how to structure components to refresh a block with data?

I am starting playing with React and trying to build a simple app where I have a list of posts and after adding a new one, this post would be added to the list. Here's what I have so far:

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

and

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

I am adding the posts to the database on a Rails backend:

def testtt
    Post.create(message: params[:form_data][:description])
    @posts = Post.order('created_at')
    render json: @posts
  end

What I struggled on - I added a new post to the database, but - how do I add this new post to the list of existing ones?

EDIT: Adding also my index.html.erb (it's only rendering there the components).

<%= react_component('Header', {title: 'Radek'}) %>

<%= react_component("HelloWorld", { greeting: "Hello" }) %>

<%= react_component("LoadModal") %>

<%= react_component("Posts") %>

First, I feel it is sor of overengineering to return all of the posts after create. So let's do something like:

@post = Post.new(params.require(:post).permit(:message))
if post.save
  render json: @post
else
  render json: @post.errors, status: :unprocessable_entity 
end

On front end try something like

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)

          })
}

in NewPost, having in mind to give it a prop onAddPost like <NewPost onAddPost={(e) => this.addPost(post, e)}/> with addPost defined like so:

addPost(post){
    const oldPosts = this.state.posts;
    this.setState({posts: oldPosts.push(post)})
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM