2016-08-18 21 views
1
const initialState: FriendsState = { 
    friends: [] 
}; 

export default function friends(state = initialState, action: Action): FriendsState { 
    switch (action.type) { 
    case TYPES.ADD_TO_FRIENDS: 
     return assign({}, state, { 
     friends: state.friends.push(action.payload.friendId) 
     }) 
    } 
} 

我基本上試圖添加一個friendId,看起來像1003或東西到我的朋友陣列。這是否是正確的方式?使用TypeScript + Lodash,你如何將某物推入數組?

如果我必須添加一個對象呢?像{ friendId: 1003, category: 4 }

export interface Friends { 
    friends: FriendIds[]; 
}; 

interface FriendIds { 
    id: number; 
} 
+0

我得到說'類型錯誤錯誤:state.friends.push不是function' – user1354934

+1

話,我想這不是一個數組,你承擔。請記住'push'不會返回結果數組,因此在某些情況下,您可能想要使用'concat'。 – 2016-08-18 18:43:52

+0

我想我正在定義我的數組錯誤然後。你能看看我的編輯嗎? – user1354934

回答

2

I am basically trying to add a friendId that looks like something like 1003 or something into my friends array. Is that the right way of going about it

push將添加到陣列中。

但它會改變數組。看到您使用Redux時(文檔:http://redux.js.org/),您希望使用非變異方法。 e.g CONCAT:

const initialState: FriendsState = { 
    friends: [] 
}; 

export default function friends(state = initialState, action: Action): FriendsState { 
    switch (action.type) { 
    case TYPES.ADD_TO_FRIENDS: 
     return assign({}, state, { 
     friends: state.friends.concat([action.payload.friendId]) 
     }) 
    } 
}