javascript - 如何从action中调用reducer中存储的变量?

标签 javascript reactjs react-native axios

我有在 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/

相关文章:

javascript - 初始化后可以更改 OpenSeaDragon 平移选项吗

Javascript 打开新窗口并加载 _self

javascript - 一个页面的多个 Google Analytics 4 脚本跟踪器

reactjs - 将 paperjs 移植到 react/nodejs 时卡住了

javascript - React + Express - 在开发时用什么服务代替/构建

android - express 端口 3000,react native 端口 8081,如何发出 get 请求

javascript - 提供给叠加层的 'children' 类型的无效 Prop 'array'。预期单个 react 元素

javascript - 如何将谷歌浏览器的 .keyIdentifier 转换为合理的东西?

javascript - 表单进度条

react-native - 是否可以在 native react 中更改滚动条颜色