LoginSignup
6
1

More than 5 years have passed since last update.

Unduxと接続したコンポーネントに追加のpropsを渡す方法

Last updated at Posted at 2018-02-16

Unduxを知らない方は以下の記事からどうぞ
【Reduxに疲れた人のための】Undux入門

前置き

Unduxに接続したコンポーネントのpropsは、基本的にはストアのデータを持つstoreという要素しか持たない。

なので、例えば以下のようにotherというpropsを追加で受け取ろうとするとTypeScriptに怒られるので、無理やりanyによる解決をするしかない用に見える。

import { connect } from 'undux';

const withStore = connect(store);

const MyComponent = withStore('users')({ store, other }: any) => {

  // ...      

});

ジェネリクスを使う

だが、実際には上のwithStoreで作られるHOCは追加でpropsに渡る要素のジェネリクスを指定できるので、以下のようにするとanyをつける必要がなくなる。

interface OtherProps {
  // ...
};

const MyComponent = 
  withStore('users')
    <OtherProps>({ store, other }) => {

      // ...      

    });

react-navigationとの例

実際のケースとして、例えばreact-navigationは、ナビゲーターにマウントされるコンポーネントのpropsnavigationという画面遷移操作のための要素を渡してくるので、Unduxと一緒に使うには以下のように工夫するとよい。

import { NavigationScreenProps } from 'react-navigation';

interface NavProps extends NavigationScreenProps<any> {}

const MyComponent =
  withStore('users')
    <NavProps>({ store, navigation }) => {

      // navigation.goBack();
      // ...

    });
6
1
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
6
1