尝试访问嵌套对象时,useContext返回未定义

时间:2020-09-22 17:40:58

标签: reactjs react-hooks

我正在使用钩子来访问数据,如果我在console.log中记录了第一级数据,我将获得所有信息,包括嵌套在初始对象中的对象。如果我尝试访问任何数据,则会返回未定义的数据。

组件访问数据

import React, { useContext, useEffect } from 'react';

import { GlobalContext } from '../contexts/GlobalState';

export default function BlogDetail(props) {
    const { blogPostToEdit, getBlogWithId } = useContext(GlobalContext);

    useEffect(() => {
        getBlogWithId(props.match.params.id)
    }, [])

    const { title, content, tags, date, userId } = blogPostToEdit;
    const parsedDate = new Date(date);
    console.log(blogPostToEdit)
    console.log(userId);
    return (
        <div className='blog-detail-wrapper'>
            <div className='blog-title'>
                {title}
            </div>
            <div className='blog-detail-date'>
                <div>{parsedDate.getMonth() + 1 + '/' + parsedDate.getDate() + '/' + parsedDate.getFullYear()}</div>
            </div>
            <div className='blog-content'>
                {content}
            </div>
            <div className='blog-tags'>
                {tags}
            </div>
        </div>
    )

上下文

import React, { createContext, useReducer } from 'react';
import axios from 'axios';

import BlogReducer from '../reducers/BlogReducer';

const initialState = {
  blogPosts: [],
  blogPostToEdit: {},
  error: null
}

export const GlobalContext = createContext(initialState);

export const GlobalProvider = ({ children }) => {
  const [state, dispatch] = useReducer(BlogReducer, initialState);

  async function getBlogPosts() {
    try {
      const res = await axios.get('http://localhost:4000/api/blogPost/getPosts');

      dispatch({
        type: 'GET_BLOGS',
        payload: res.data
      })
    } catch (err) {
      dispatch({
        type: 'FETCH_ERROR',
        payload: err.resposonse.data.error
      })
    }
  }

  async function getBlogWithId(id) {
    try {
      const res = await axios.get(`http://localhost:4000/api/blogPost/getPostById/${id}`);

      dispatch({
        type: 'GET_BLOG_ID',
        payload: res.data
      })
    } catch (err) {
      dispatch({
        type: 'FETCH_ERROR',
        payload: err.resposonse.data.error
      })
    }
  }

  return (
    <GlobalContext.Provider value={{
      blogPosts: state.blogPosts,
      blogPostToEdit: state.blogPostToEdit,
      auth: state.auth,
      error: state.error,
      getBlogPosts,
      getBlogWithId
    }}>
      {children}
    </GlobalContext.Provider>
  )
}

减速器

export default (state, action) => {
  switch (action.type) {
    case 'GET_BLOGS':
      return {
        ...state,
        blogPosts: action.payload
      }
    case 'GET_BLOG_ID':
      return {
        ...state,
        blogPostToEdit: action.payload
      }
    default: return state;
  }
}

这就是数据的样子

blogPostToEdit:{
content: "Right now I'm all stressing it out because I can't seem to know how to work with state and..."
date: "2020-01-02T01:18:04.488Z"
tags: ["RouterLink, Javascript, react, dummydumtime"]
title: "This is whole new blog for a whole new year"
userId:{
    date: "2019-08-27T23:27:42.945Z"
    email: "gloob@email.com"
    name: "gloob"
    password: "***"
    _id: "5d65bc6e4402213647f8704b"
}
_id: "5e0d44cc5ba6ddb32418c760"
}

我想做的就是访问该名称,但是当我尝试使用它时,它会返回未定义的名称。这可能是一个重复的问题,但我似乎找不到答案。谢谢

0 个答案:

没有答案
相关问题