无法弄清楚为什么数据不会加载到React组件中

时间:2016-08-03 19:20:15

标签: javascript reactjs mongoose 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();

当我从帮助函数中发布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;

1 个答案:

答案 0 :(得分:0)

我不会按原样使用您的 var ccs = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260'] // FSFL = F*Simple For-Loop var sum = (a, b) => a + b; var largestSum = 0; var largestSumLastIdx = 0; for (let i = 0; i < ccs.length; i++) { let s = ccs[i].split(/-|/).map(Number).reduce(sum, 0); if (s >= largestSum) { largestSum = s; largestSumLastIdx = i; } } console.log("The winner is: " + ccs[largestSumLastIdx])。而是直接使用你的助手:

PostStore