React useEffect没有来自Context API的更新状态数据

时间:2020-04-08 17:34:57

标签: reactjs react-context use-effect contentful use-context

为什么我的应用程序无法从useEffect中的状态获取最新数据?

我有一个组成部分。 Article.js ,它使用useContext导入上下文。

Codesandbox

import React, { useContext, useEffect } from "react";
import ArticleContext from "../../context/article/articleContext";
import Spinner from "../layout/Spinner";
import { documentToHtmlString } from "@contentful/rich-text-html-renderer";

const Article = ({ match }) => {
  const articleContext = useContext(ArticleContext);
  const { getArticle, loading, article } = articleContext;
  useEffect(() => {
    getArticle(match.params.slug);
  }, []);

  /**
   * When i use article anywhere here, it is undefined.
   */

// this will be undefined
console.log(article); 
// Even though getArticle has updated the state via the reducer.


  if (loading) {
    return <Spinner />;
  } else {
    return (
      <main>
        <section className='container'>
          {/* the idea is to put the content here */}
        </section>
      </main>
    );
  }
};

export default Article;

这是我在名为 articleState.js

的文件中的上下文
import React, { useReducer } from "react";
import ArticleContext from "./articleContext";
import ArticleReducer from "./articleReducer";
import { SET_LOADING, GET_ARTICLE } from "../types";

import client from "../../contentful";

const ArticleState = props => {
  //Initial State
  const initialState = {
    article: {},
    loading: false
  };

  // Set the reducer we want to use
  const [state, dispatch] = useReducer(ArticleReducer, initialState);

  //set up your actions

  //set loading
  const setLoading = () => {
    dispatch({ type: SET_LOADING });
  };

  //get a single article
  const getArticle = async slug => {
    setLoading();
    const res = await client.getEntries({
      content_type: "article",
      "fields.slug": slug
    });
    dispatch({ type: GET_ARTICLE, payload: res.items });
  };

  return (
    <ArticleContext.Provider
      value={{
        article: state.article,
        loading: state.loading,
        getArticle
      }}
    >
      {props.children}
    </ArticleContext.Provider>
  );
};

export default ArticleState;

在检查chrome开发人员工具栏时,状态会成功更新。我看到我从满足感中删除的文章内容。它处于我的状态。

Chrome developer toolbar - React component state

我唯一的问题是,当我尝试从文章获取数据时,它是未定义的。

这是我的减速器 articleReducer.js

import { SET_LOADING, GET_ARTICLE } from "../types";

export default (state, action) => {
  switch (action.type) {
    case SET_LOADING:
      return {
        ...state,
        loading: true
      };
    case GET_ARTICLE:
      return {
        ...state,
        article: action.payload,
        loading: false
      };
    default:
      return state;
  }
};

感谢您阅读本文档以及获得任何帮助。

0 个答案:

没有答案