4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

redux-formのFieldの値の更新に処理を差し込む

Last updated at Posted at 2016-12-27

2017-01-31 redux-formで対応

Event callbacks!

Yay!
6.5.0以降は単純に以下でOK

<div>
  <Field name='test_name' component='select' onChange={e => this.setState({test_state: e.target.value})} >
    <option value='test'>test</option>
    <option value='test2'>test2</option>
  </Field>
  {(this.state || {}).test_state === 'test'? 'テスト' : 'テストでない'}
</div>

e.preventDefault()でredux-formの処理をさせないようにもできる。(選ばせたくない時なんかに使う?)
これにて一件落着。

やりかた

Componentを作る処理を書いて、onChangeの処理を上書きする。こういう感じ

render() {
  const bindStateSelect = ({input: {onChange, ...inputs}, children: children, bindState: bindState}) => 
    <select onChange={
      e => {
        const o = {};
        o[bindState] = e.target.value;
        this.setState(o);
        onChange(e);
      }
    } {...inputs}>{children}</select>

  return (
    <div>
      <Field name='test_name' component={bindStateSelect} bindState='test_state'>
        <option value='test'>test</option>
        <option value='test2'>test2</option>
      </Field>
      {(this.state || {}).test_state === 'test'? 'テスト' : 'テストでない'}
    </div>
  )
}

FieldonChangeに直接渡すと、それで上書きされて全く使えない状態になる。色々探っているうちにこういう形になった。
onChangeが指定されてたらhandleChangeを後ろにくっつけるみたいな生成にしてくれたら、こういうことはしなくて良くなるんじゃないかと思うんですが……

経緯

Fieldの値が変わったら描画内容を変えるのをやりたかった。例は文言変わるだけですが実際は出すcomponentを変えたりする形です。

正攻法ならreducerを追加してやることになると思う。
まず、Fieldを使わずに自分でactionを呼ぶコードをonChangeで書き、submitの中でマージする。これには何のためにredux-form使っているのかという迷いがあります。(ちょっと凝ったことをするとこうなるけど)
次に、Fieldの値変更時に@@redux-form/CHANGEというactionが投げられるので、reducer内で拾って処理する。良さそうな気がしますが、ドキュメントに書いてあるわけではないのでバージョン上げたら動かないとかなりそう。
なので、ひとまず上の方法を考えてみた。

こういうのやってると小さいreducerがいっぱいできて、実害はともかくウーンという感じになる。簡単な画面切り替え程度を手軽にやるならこんなもんで……。この辺も見つつ
http://qiita.com/rchaser53/items/41a6a149ca00cf405eca

思ってたより苦戦したので備忘録まで

4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?