简体   繁体   中英

Cannot figure out why data won't load into React component

Here is my store:

import helper from './../../helpers/RestHelpers.js';

var posts = [];

class PostStore {

    constructor() {
        helper.get('/api/posts')
            .then((data) => {
                posts = data;
                console.log(posts);
            }
        );
    }

    getPosts() {
        return posts;
    }

};

export default new PostStore();

When I console.log posts from within the helper function, I get the correct data. But when I console.log from the component, the array of posts is empty.

Here is my component:

import React from 'react';

import postStore from '../stores/PostStore';

class Home extends React.Component {

    constructor() {
        super();
        this.state = {
            posts: postStore.getPosts()
        }
        console.log(this.state.posts);
    }

    render() {
        return (
            <div className="welcome">
                {this.state.posts.map(function(post, index) {
                return (
                        <PostItem post={post} key={"post " + index} />
                    )
                })
            }
            </div>
        )
    }
}

class PostItem extends React.Component {
    render() {
        return <div>{this.props.post.postName}</div>;
    }
}

export default Home;

I wouldn't use your PostStore as-is. Instead just use your helper directly like so:

import React from 'react';
// import your helper!

class Home extends React.Component {

    componentDidMount() {
      helper.get('/api/posts').then((data) => {
        this.setState({posts: data})
      });
    }

    render() {
        return (
            <div className="welcome">
              {this.state.posts.map((post, idx) => <PostItem post={post} key={"post " + idx} />)}
            </div>
        )
    }
}

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