2017-06-19 25 views
0

我的反應+ redux應用程序需要在商店中存儲用戶配置文件。示例數據:有了React + Redux,我應該如何在商店中存儲配置文件?

{"user_id":11,"stuff":"more stuff"}, {"user_id":313,"stuff":"more stuff"},{"user_id":13111,"stuff":"more stuff"},{"user_id":21,"stuff":"more stuff"} 

我應該如何將此存儲在我的商店中?如果有幫助,我可以重新格式化上述數據?

我需要store.profiles來存儲一個或多個配置文件,它可能包括current_user的配置文件。

然後,我需要我的Profile組件能夠在組件渲染時在存儲中查找或獲取current_user的配置文件。我應該如何處理這個問題?

謝謝,我的新反應+終極版

+0

您是否需要同時使用多個用戶配置文件?如果沒有,那麼只需在商店中有一個密鑰來「存儲」一個用戶。如果你這樣做了,你需要使用'mapStateToProps'來查找/獲取current_user的配置文件(就像你在上一個問題中那樣)來篩選正確的用戶配置文件。 –

+0

我將需要一次超過一個配置文件... – AnnaSm

回答

1

如果我在我的應用程序設計簡介,我會做類似下面的代碼。在這種情況下,我將用戶保存在一個數組中。或者,您可以使用一個對象或Map

// reducer 
 
function userReducer(state = [], action) { 
 
    switch(action.type) { 
 

 
    // adding new user, just append to the end of array 
 
    case ADD_USER: 
 
     return [...state, {...action.payload.user }] 
 
    
 
    // editing an existing user, must check if exists! Othewise return original state 
 
    case EDIT_USER: 
 
     const filteredUsers = state.filter(user => user.id === action.payload.user.id); 
 
     const isUserExist = filteredUsers.length > 0; 
 
     if (isUserExist) { 
 
     const updatedUser = { ...filteredUsers[0], ...action.payload.user }; 
 
     return [...state.filter(user => user.id !== action.payload.user.id), updatedUser]; 
 
     } else { 
 
     return state; 
 
     } 
 
     
 
    default: 
 
     return state; 
 
    } 
 
} 
 

 
// sample user obj 
 
{ 
 
    id: 'unique-id', 
 
    first_name: 'bob', 
 
    last_name: 'jones', 
 
    email: '[email protected]', 
 
    photo_url: 'some url', 
 
    bio: 'some text' 
 
} 
 

 
// container.js 
 
const mapStateToProps = (store) => ({ 
 
    users: state.users, 
 
    getUser: (userId) => state.users.filter(user.id === userId), 
 
}); 
 

 
const mapDispatchToProps = (dispatch) => ({ 
 
    editUser: (userId) => dispatch(editUser(userId)) 
 
}) 
 

 
// actions.js 
 
import uuid from 'uuid/v4'; 
 

 
function editUser(payload) { 
 
    return { 
 
    type: 'EDIT_USER', 
 
    ...payload 
 
    } 
 
} 
 

 
function addUser(user) { 
 
    return { 
 
    type: 'ADD_USER', 
 
    payload : { 
 
     user: { 
 
     ...user, 
 
     id: uuid() 
 
     } 
 
    } 
 
    } 
 
} 
 

 
// probably shouldn't edit id 
 
payload { 
 
    id: 'uniquestring', 
 
    first_name: 'momo', 
 
    last_name: 'wawa', 
 
    // ... the rest of the changes 
 
}

這假定您已經知道了終極版的基礎知識。否則,請閱讀this tutorial

+0

謝謝,在這個例子中,userId被設置在哪裏? – AnnaSm

+1

我編輯了我的答案。我會在reducer中使用uuid庫創建它:https://www.npmjs.com/package/uuid。一旦用戶設置了id,就不應該改變它。 –

+1

請注意,在減速器中生成新的UUID是不鼓勵的,因爲減速器不再是純函數。代碼將運行,但在時間行程調試下測試並不能正確工作。理想情況下,動作創建者應該生成隨機值 - 請參閱https://daveceddia.com/random-numbers-in-redux/。 – markerikson

相關問題