2017-01-18 5 views
0

immutability helperを使用して、オブジェクトの配列内の各値を変更するのがベストプラクティスであることを理解するのは難しいです。私は私の状態でこれを持っているとしたら例えば不変性ヘルパーで配列の各値を変更する

、:

this.state = { 
    items: [ 
     { 
      name: "test", 
      subItems: [ 
       {val: false}, {val: true}, {val: false} 
      ] 
     }, 
     { 
      name: "test2", 
      subItems: [ 
       {val: true}, {val: true}, {val: false} 
      ] 
     } 
    ] 
} 

そして、私はすべてのvalfalseに設定したい、私はそれをどのように行うかもしれません。

私は一度それを1つずつ行うことができますが、より良い方法がなければならない:

let elements = update(this.state.items, { 
    [idx1]:{ 
    subItems:{ 
     [idx2]:{ 
     val: { 
      $set: false 
     } 
     } 
    } 
    } 
}); 

答えて

2

それは確かに可能ですが、それは一目で読めるか理解できるが、すべてのものです。

const nextState = update(state, { 
    items: { 
    $apply: (items) => { 
     return items.map(item => { 
     return update(item, { 
      subItems: { 
      $apply: (subItems) => { 
       return subItems.map(subItem => { 
       return update(subItem, { 
        val: { 
        $set: false 
        } 
       }) 
       }) 
      } 
      } 
     }) 
     }) 
    } 
    } 
}); 
+0

falseと真のboolの組み合わせを、すべてfalseに設定することに反対に設定するとどうなりますか?これを行うためのエレガントな方法? – ahmedhosny

0

ES6の不変性を持つソリューション、destructuringなしヘルパーについては、この

this.state = { 
    items: [ 
     { 
      name: "test", 
      subItems: [ 
       {val: false}, {val: true}, {val: false} 
      ] 
     }, 
     { 
      name: "test2", 
      subItems: [ 
       {val: true}, {val: true}, {val: false} 
      ] 
     } 
    ] 
} 

使用関数型プログラミング

this.state.items 
.filter((item) => item.name === test).subitems 
.map((subItem) => { 
    subitem.forEach((key) => { 
    { [key]: !subitem[key] } 

}) 
}) 
+0

私はOPが 'this.state'を更新したいと思っていますが、古いものを完全な状態に戻すことはありません。 – bebbi

0

を試してみてください。

this.setState({ 
    // This is if you have other state besides items. 
    ...this.state, 
    items: this.state.items.map(item => ({ 
    ...item, 
    subItems: item.subItems.map(subItem => ({ 
     ...subItem, 
     val: false // or e.g. setter as a function of (item, subItem) 
    })) 
    })) 
}); 

が私の目に簡単ですそのn更新ヘルパー。

関連する問題