【问题标题】:how to get userid in redux action?如何在 redux 操作中获取用户 ID?
【发布时间】:2020-05-03 09:43:28
【问题描述】:

我正在尝试仅打印与用户相关的项目。 所以我尝试通过向用户 ID /api/items/:userid 请求数据来获取项目 我正在使用 redux 商店

我的服务器端代码是这样的

router.get("/:userid",(req, res) => {
  // Item.find({ "owner.ownerName": `${req.params.userid}`})
  Item.find({ "owner.id": `${req.params.userid}`})
    .sort({
      date: -1,
    })
    .then((items) => res.json(items));
   console.log(req.user)
});

问题是我的前端请求。 我不知道如何在 ITEMACTION 中获取用户 ID。

import {
  GET_ITEMS,
  ADD_ITEM,
  DELETE_ITEM,
  ITEMS_LOADING,
  UPDATE_ITEM,
  SUBSTRACT_ITEM,
} from "../actions/types";
import { tokenConfig } from "../actions/authActions";
import { returnErrors } from "../actions/errorActions";
import Axios from "axios";

export const getItems = () => (dispatch) => {
  // will hit reducer
  dispatch(setItemsLoading());
  Axios.get("/api/items/")
    .then((res) =>
      dispatch({
        type: GET_ITEMS,
        payload: res.data,
      })
    )
    .catch((err) => {
      dispatch(returnErrors(err.response.data, err.response.status));
    });
};

我实际上试图从 redux 商店获取用户 ID。

import store from '../store';

在 getItems 内部

store.getState().auth.user._id

问题是,当我在 getItems 中 console.log 时,用户 id 总是返回 null,除了登录后的第一次。但是当我查看 redux 开发工具时。用户ID可用

如何获取用户名

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    嘿,您可以将 getState 作为内部函数的第二个参数与调度一起获取,使用它您可以访问操作中的更新状态。 固定代码:

    export const getItems = () => (dispatch, getState) => {
      // will hit reducer
      const userId = getState().auth.user._id;
      console.log(userId) // should output the updated data
      dispatch(setItemsLoading());
      Axios.get("/api/items/")
        .then((res) =>
          dispatch({
            type: GET_ITEMS,
            payload: res.data,
          })
        )
        .catch((err) => {
          dispatch(returnErrors(err.response.data, err.response.status));
        });
    };
    

    store.getState 不返回更新状态,为了使用 store.getState() 获取更新状态,您需要订阅状态更改。

    const unsubscribe = store.subscribe(() => {
        // logs the state data everytime an action is dispatched.
        console.log("from listener: ", store.getState());
    })
    

    Details here

    【讨论】:

      猜你喜欢
      • 2022-11-01
      • 1970-01-01
      • 2018-08-19
      • 1970-01-01
      • 2016-08-01
      • 2011-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多