2016-07-17 20 views
1

正常に動作していた単純な減速状態を持っています。 M減速機は以下の通りです。更新後にRedux状態が未定義のまま返される

const initialState = 
{ 
plan: [ 
    { 
     id: 0, 
     text: 'Submit math assignment at noon.', 
     completed: false 
    } 
] 
} 
function mytodo(state = initialState, type) { 
    switch(type) { 
     ... 
     default: 
      return state;  
    } 
} 

アプリが正常に動作します。次に、いくつかのローカルストレージデータを自分の状態に連結します。私の状態は未定義に戻ります。

const storageItems = JSON.parse(localStorage.getItem('plan')); 

function mytodo(state = initialState, type) { 
     switch(type) { 
      ... 
      default: 
       console.log('the storage data is', storageItems); 
       return storageItems ? state.plan.concat(storageItems) : state;  
     } 
    } 

上記のストレージアイテムにデータがあることを確認しましたが、私のレデューサーは計画通りにコンポーネントに戻りました。私はこれを次のように変更しました。

const storageItems = JSON.parse(localStorage.getItem('plan')); 
if(storageItems) { 
    initialState = initialState.todos.concat(storageItems); 
    console.log('the states are', initialState); 
} 

function mytodo(state = initialState, type) { 
     switch(type) { 
      ... 
      default: 
       return state;  
     } 
    } 

とし、initialStateをletに変更します。それでも未定義です。上のコンソールからの初期状態は、必要な完全な結果を返します。しかし、initialStateを更新すれば、コンポーネントに値を返しません。私は間違って何をしていますか?私はこれにどのように対処しましたか?どんな助けもありがとう。

答えて

1

Array.prototype.concat()は、新しい配列オブジェクトhttps://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concatを返します。エラーが発生した場所を確認します。オブジェクトは空ではなく、順序が変更されている可能性があります。

const initialState = 
{ 
plan: [ 
    { 
     id: 0, 
     text: 'Submit math assignment at noon.', 
     completed: false 
    } 
] 
} 

上記から、initialState.planはプラン配列を返す必要があります。

しかし、

initialState = initialState.todos.concat(storageItems); 

は、新しい配列を返します。あなたの状態が変更されたため、未定義のエラーを投げるでしょうどこでもあなたのstate.planを持っている場合今、あなたの初期状態は、したがって、フォーム

initialState = [{ 
      id: 0, 
      text: 'Submit math assignment at noon.', 
      completed: false 
     }] 

を取るだろう。 concatについてここに欲しいhttps://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

関連する問題