2017-04-10 5 views
0

javascriptでの割り当てとマージの違いを十分に理解しているかどうかは疑問です。以下の減速は、状態を更新するたびに、私はエラーが消え、別の方法でnewKeyframesを計算する場合、私は、しかしEncountered two children with the same keyエラー同じキーの子供:Object.assign vs _.merge

function updateKeyframes(state, action) { 
    const { keyframeIds, props } = action.payload; 

    const newKeyframes = _.map(keyframeIds, function(id) { 
    return _.merge(state.keyframes[id], props); 
    }); 

    return Object.assign({}, state, { 
    keyframes: Object.assign({}, state.keyframes, newKeyframes) 
    }); 
} 

を取得します。

const newKeyframes = keyframeIds.reduce((memo, keyframeId) => 
Object.assign({}, memo, { 
[keyframeId]: Object.assign({}, state.keyframes[keyframeId], props) 
}), {}); 

なぜですか?ここで何が起こっているのですか?

+2

'_.merge'は再帰的です。データを表示しないと、違いを確認するのは難しいです。また、オブジェクトの '_.map'はあなたが期待するものとは非常に異なるものです。値を '配列'にマップします。つまり、あなたの 'id'は' id 'でもなく、結果はオブジェクトではなく配列です。 – Sulthan

+0

あなたは正しいです、助けてくれてありがとう。 state.keyframesを配列ではなくオブジェクトに設定したかったのです。 –

答えて

1

最初の例では、newKeyframesは配列です。あなたの2番目の例では、newKeyFramesがオブジェクトです。予想通り

Object.assign({}, state.keyframes, newKeyframes) 

newKeyFramesが配列の場合、キーの交換はおそらく行くことはありません。明らかな違いがで、その後があります。

+0

reduce: const newkeyframes = _.reduce(keyframeIds、function(result、id){ result [id] = _.merge(state.keyframes [id]、props); 戻り値を使用してオブジェクトを作成しました。 }、{}); –

関連する問題