1

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

我有一个组件。使用useContext导入上下文的 Article.js。

代码沙盒

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 开发者工具栏 - React 组件状态

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

这是我的减速器文章Reducer.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;
  }
};

感谢您阅读本文并提供任何帮助。

4

0 回答 0