簡體   English   中英

無法弄清楚為什么數據不會加載到React組件中

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

這是我的商店:

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();

當我從helper函數中進行console.log發布時,我得到了正確的數據。 但是,當我從組件進行console.log時,帖子數組為空。

這是我的組件:

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;

我不會PostStore原樣使用您的PostStore 而是直接像這樣直接使用您的助手:

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>
        )
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM