2016-07-26 100 views
0

我使用Redux來創建我的分頁。我的問題是,在constructor我運行了一個方法,將解析URL並檢查是否有任何關於分頁。然後它運行一個將數據放入我的商店的操作。這一切運行順利。React - 構造函數()和componentDidMount

然後,我有componentDidMount方法,當我運行另一個操作 - 獲取數據。在那裏我使用了我以前推過的道具。不幸的是,商店處於初始狀態。

我(簡化)代碼:

class NewsList extends React.Component { 
    constructor(props) { 
     super(props); 

     this.profile = document.getElementById('articles').getAttribute('data-profile'); 

     this.parseHash(); 
    } 

    parseHash() { 
     /* Method for parsing navigation hash 
     ---------------------------------------- */ 
     const hash = window.location.hash.replace('#', '').split('&'); 

     const data = { 
      page: 1, 
      offset: 0 
     }; 

     // hash parsing 

     this.props.setPagination(data); 
    } 

    componentDidMount() { 
     this.loadNews(); 
     // If I use 
     // setTimeout(() => { this.loadNews(); }) 
     // it works, but I feel this is hack-ish 
    } 

    loadNews() { 
     this.props.update({ 
      current: {page: this.props.NewsListReducer.current.page, offset: this.props.NewsListReducer.current.offset}, 
      next:  {page: this.props.NewsListReducer.next.page, offset: this.props.NewsListReducer.next.offset} 
     }); 
    } 
} 

當我console.log(this.props.NewsListReducer),我越來越undefined兩個currentnext對象,但是當我使用終極版DevTools,數據是存在的。我能做什麼?

+0

嘗試將this.parseHash()移入componentWillMount() – jzm

+0

這與@jzm相同。 'constructor'就像'componentWillMount()'的替代品。 –

+1

純粹的反應。但是對於redux,請參閱最後一個答案:http://stackoverflow.com/a/37703446/769083 – jzm

回答

0

看起來有些地方存在某種異步性。你可能正在使用react-redux吧?我認爲這個異步來自connect ed組件,因爲它使用setState when the store state has changedsetState安排異步狀態更新。

因此this.props.NewsListReducer不是最新的componentDidMount()

我猜this.props.update是一個會取消新聞的動作,對不對?爲什麼您需要從組件向它提供分頁信息?例如。使用redux-thunk,您可以在分派操作之前訪問商店狀態。這可能是您閱讀(最新)分頁信息的機會。

E.g.

export function fetchNews() { 
    return (dispatch, getState) => { 
    getState().NewsListReducer.current.page; // Up to date 

    ... 

    fetch(...).then(() => 
     dispatch({...})); 
    } 
} 

Btw。不要打電話給你的國家*Reducer可能是個好主意。它是管理國家的減速機,但減速機不是這種狀態的一部分。