我有一个React应用程序向Rails API发出请求。用户签名的代码如下所示: “./actions/userActions”
export function signInUser(user){
var data = {email: user.email, password: user.password, remember_me:
user.id};
return function(dispatch){
dispatch({type: 'SIGN_IN_USER', payload: user})
return fetch('https://fidirect-api.herokuapp.com/api/users/sign_in', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({user: data}),
}).then(res => console.log(res))
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
}
减速机看起来像这样:
export function usersReducer(state = {currentUser: {}, user_id: null}, action) {
switch (action.type) {
case 'SIGN_UP_USER':
window.localStorage.setItem('id', 'action.id')
return Object.assign({}, state, {currentUser: {id: action.id, email: action.email, password: action.password },
user_id: window.localStorage.getItem('id') })
case 'SIGN_IN_USER':
return Object.assign({}, state, {currentUser: {id: action.payload.id, email: action.payload.email, password: action.payload.password }, user_id: current_user.id})
default:
return state
}
}
这样可以正常工作,但我希望能够将存储在后端的用户ID(例如1,2,3,4等)保存到前端,以便将来在我请求特定用户的数据,我可以根据用户的ID过滤数据,这看起来像这样: “./reducers/assetsReducer”
case 'GET_ASSETS':
return {loading: false, assets: action.payload.filter((asset => asset.id === getState().usersReducer.user_id))};
default:
return state;
}
如何在React中保留这样的用户ID?
答案 0 :(得分:0)
您使用localstorage作为注册减速器(不确定原因)但您也可以这样做以登录。登录后将数据保存到localstorage,或者使用react store。