2016-08-03 43 views
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; 
+2

你的helper.get('/ api/posts')是一個ajax請求。當構造函數加載它時,它不會等待實際獲取數據。 – Shaunak

+0

我該如何設置它以等待數據被提取? – bounty

+0

如果你在jsfiddle上創建一個小的工作示例來複制問題,這將有所幫助。 – Shaunak

回答

0

我不會用你的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> 
     ) 
    } 
} 
+0

爲什麼這個代碼在reactjs上工作,但是相同的代碼在反應本機上無法工作? http://stackoverflow.com/questions/39295108/reactjs-listview-to-react-native-listview – TeodorKolev