2016-07-26 12 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} 
     }); 
    } 
} 

I console.log(this.props.NewsListReducer)、私は両方currentnextオブジェクトに対してundefinedを取得していますが、私はReduxのデベロッパーツールを使用する場合、データがあります。私に何ができる?

+0

this.parseHash()をcomponentWillMount()に移動してみてください。 – jzm

+0

これは@jzmと同じです。 'constructor'は' componentWillMount() 'の代わりです。 –

+1

純粋な反応のため。しかし、reduxのために、ここでの最後の答えを参照してください:http://stackoverflow.com/a/37703446/769083 – jzm

答えて

0

どこかに非同期性があるようです。あなたはおそらく反応還元型の権利を使用していますか?私は、setState when the store state has changedを使用しているので、非同期性がconnect edコンポーネントから来ていると思います。 setStateは、非同期状態アップデートをスケジュールします。

したがって、this.props.NewsListReducercomponentDidMount()に更新されていません。

私はthis.props.updateがニュースをフェッチするアクションだと思いますか?コンポーネントからページング情報を提供する必要があるのはなぜですか?例えば。あなたはアクションをディスパッチする前に店舗の状態にアクセスすることができます。これは、(最新の)ページング情報を読むチャンスです。

など。

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

    ... 

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

Btw。あなたの状態を*Reducerと呼ぶのは良い考えです。状態を管理するのは減速機ですが、減速機はそのように状態の一部ではありません。

関連する問題