无法使用React Hooks读取Redux中的状态,无法读取null的属性'_id'

时间:2020-03-11 17:36:26

标签: javascript reactjs redux react-redux react-hooks

我有一个MERN网络应用程序,正在学习React Hooks。

我要做什么:访问Redux中的状态。

刷新页面时, 错误:TypeError: Cannot read property '_id' of null

当我在redux开发人员工具中清楚地看到状态时,我将无法访问它。 我已经尝试过console.log(auth.isAuthenicated),但是它返回了null。但是,当我执行console.log(auth)时,它将返回[object,object]。这让我感到困惑,因为我无法进去。

目前,我正在研究并将研究react-persist。我想知道是否有人可以在没有任何反应的情况下帮助我解决我的问题,还是要解释为什么使用它可能是一个好主意。

我的redux:

token(pin):"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlNDFmYTNhOWIwZjk0NmU5N2Q5MmY4MiIsImlhdCI6MTU4Mzk0NzA5MSwiZXhwIjoxNTgzOTUwNjkxfQ.pysX20n4cxKK5NqcXPosIejSvCN3pbcSNpQvEOX9kBE"
isAuthenticated(pin):true
isLoading(pin):false
_id(pin):"5e41fa3a9b0f946e97d92f82"
name(pin):"admin"
email(pin):"admin@gmail.com"
date(pin):"2020-02-11T00:50:02.183Z"
__v(pin):0 

我的代码段:

import React, { useState, useEffect } from "react";
import { TiDelete } from "react-icons/ti";
import Restaurants from "../Restaurant/Restaurants";
import NutritionalGraphs from "../D3Graphs/NutritionalGraphs";
import { connect, useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { addItem, deleteItem } from "../../../actions/itemActions";
import IngredientsPredictions from "../Predictions/IngredientsPredictions";
import { loadUser } from "../../../actions/authActions";

import { createSelector } from "reselect";

const UserProfile = props => {
  const dispatch = useDispatch();

  const [newUserFavorite, setNewUserFavorite] = useState("");
  const [favArray, setFavArray] = useState([]);
  const tokenRecognized = useSelector(state => state.auth.token);

  // const userID = useSelector(state => state.auth.user._id);
  const auth = useSelector(state => state.auth);

  const userStates = createSelector();
  // name
  // name => props.auth.user.name,
  // userID => props.auth.user._id
  // foodFavoritesArray => foodFavoritesArray.state.item.items

  useEffect(() => {
    dispatch(loadUser(tokenRecognized));
    // console.log(userStates.userID);
    console.log(auth.isAuthenicated);

    axios
      // .get(`/api/items/item/${userStates.userID}`)
      .get(`/api/items/item/${auth.user._id}`)
      .then(res => {
        return res.data;
      })
      .then(json => {
        setFavArray(json);
      })
      .catch(err => console.log(err));
  }, [userStates.userID]);
  console.log(favArray);

它在.get(`/api/items/item/${auth.user._id}`):

处中断

非常感谢您的阅读。

1 个答案:

答案 0 :(得分:0)

您需要等待var answer = contrats.GroupBy(c => c.id_clientGestion) .Select(cg => cg.Select(c => c.id_contrat)); 操作完成才能访问数据。我假设它发出了一个异步请求。您需要分两个步骤进行操作:

loadUser