我有在 authActions.js 中生成的变量 user_id 和 token,但我需要在不同 js 文件的更多函数中重用它们。
如何在生成后将其存储在 session 中并在注销时将其删除?
export function loginUser(email, password) {
return function (dispatch) {
return axios.post(SIGNIN_URL, { email, password }).then((response) => {
var { user_id, token } = response.data;
dispatch(authUser(user_id, token)); // here I dispatch the values to authUser const in the same file
onSignIn(user_id);
}).catch((error) => {
dispatch(addAlert("Could not log in."));
});
};
}
export const authUser = (user_id, token) => {
return {
type: 'AUTH_USER',
user_id,
token
}
}
我的 authReducer.js
var defaultState = {
user_id: undefined,
token: undefined
}
module.exports = (state=defaultState, action) => {
switch(action.type) {
case 'AUTH_USER':
return {
user_id: action.user_id,
token: action.token
}
case 'UNAUTH_USER':
return {
user_id: undefined,
token: undefined
};
default:
return state;
}
}
这是我的 jobsAction.js,我想在其中使用它们
export function createJob(title, company, avatar, description ) {
return function (dispatch) {
return axios.post(JOBS_URL(user_id), { title, company, avatar, description }, {
headers: { authorization: token }
}).then((response) => {
dispatch(addJob(response.data.job));
}).catch((err) => {
console.log(err);
dispatch(addAlert("Couldn't create job."));
});
};
}
最佳答案
您正在操作创建器中获取它,因此使用 userId
调度一个操作,并将其存储在 redux 状态中。然后您就可以从该状态获取它并在任何您想要的地方使用。
关于javascript - 如何从action中调用reducer中存储的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50003049/