0
這裏是我的商店:想不通爲什麼數據將不會加載到陣營組件
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;
你的helper.get('/ api/posts')是一個ajax請求。當構造函數加載它時,它不會等待實際獲取數據。 – Shaunak
我該如何設置它以等待數據被提取? – bounty
如果你在jsfiddle上創建一個小的工作示例來複制問題,這將有所幫助。 – Shaunak