LoginSignup
1
3

More than 5 years have passed since last update.

Javascriptで処理のスタック

Last updated at Posted at 2017-04-20

最近、react,fluxの案件にアサインされました。
こんなコードを見つけました。

    // セッションストレージからデータ取得
    const storageData = セッションストレージから取得する関数
    if (storageData !== undefined) {
      Promise.resolve().then(() => {
        // 取得したデータをStoreに保管
        AppDispatcher.dispatch({
          type: ActionTypes.SET_HOGE,
          data: storageData,
        });
      });
      return;
    }

Promise.resolve()いる?
私はそう思いました。
結果、必要でした。

componentでは以下のような処理が行われていました。

  componentWillMount() {
    this.setState({
      data: [],
    });
  }

 componentWillReceiveProps(nextProps) {
    const { obj } = nextProps;

    const list = obj.map((data, index) => (
      {
         データの整形処理
      }
    ));
    this.setState({
      data: list,
    });
  }

  return (
    this.state.dataを表示
  );

そうなんです、初期状態はstateが空なんです。
propsが更新されたら、stateを更新して、そこでやっとデータが表示されるわけです。
mountされる時は componentWillReceiveProps が呼ばれないので、stateはからのまま。
なので、Promise.resolve()で一旦データを渡す処理をスタックして、componentをmountさせてからデータを渡す処理を実行させて、componentWillReceivePropsを実行させるわけです。

わかりにくくて申し訳ないです。
自分用のメモなのでそこらへんは勘弁してくだせえ。

私が思ったこと:
スタックが目的ならsetTimeout({},0);でよくない?
そっちの方がわかりやすくない?
Promiseの方がナウいのかな?

初めてのReactむずい

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3