【问题标题】:How to fetch data and store in React Context API?如何获取数据并存储在 React Context API 中?
【发布时间】:2021-04-28 20:26:56
【问题描述】:

第一次使用 Context API,请多多包涵。

我有一个本地 JSON 文件,我正在尝试从中获取响应并将其放置在 Context API 中,以便我可以在应用程序中全局使用。

在本地运行应用程序时,出现一个空白屏幕并且页面似乎没有加载。该页面处于无限循环中,因此我看不到它是否正在加载。

代码沙盒here

知道我可以进行哪些更改以成功将数据响应引入 Context API 吗?

apiContext.js:

import React, { useContext, useState, useEffect, createContext } from "react";
import axios from "axios";

const APIContext = createContext();

function APIContextProvider({ children }) {
  // Initialize state
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  // Fetch data
  useEffect(() => {
    let url = "../db.json";
    axios
      .get(url)
      .then(function (response) {
        setData(response.data.machines);
        setIsLoading(false);
        console.log(response.data.machines);
      })
      .catch((error) => console.log(error));
  }, []);

  return (
    <APIContextProvider value={{ data }} loading={isLoading}>
      {children}
    </APIContextProvider>
  );
}

export default APIContextProvider;

// Create a hook to use the APIContext, this is a Kent C. Dodds pattern
export function useAPI() {
  const context = useContext(APIContext);
  if (context === undefined) {
    throw new Error("Context must be used within a Provider");
  }
  return context;
}

App.js:

import "./App.css";
import List from "./List";
import APIContextProvider from "./context/apiContext";

function App() {
  return (
    <APIContextProvider>
      <div className="App">
        <List />
      </div>
    </APIContextProvider>
  );
}

export default App;

List.js:

import React from "react";
import { useAPI } from "./context/apiContext";

const FetchData = ({ isLoading }) => {
  // Grab data from useAPI in global context
  const { data } = useAPI();

  return (
    <div>{!isLoading ? <p>{data[0].category}</p> : <p>Loading...</p>}</div>
  );
};

export default FetchData;

【问题讨论】:

    标签: javascript reactjs axios react-context


    【解决方案1】:

    试试这个。

    // apiContext.js
      return (
        <APIContext.Provider value={{ data, isLoading }}>
          {children}
        </APIContext.Provider>
      );
    
    // List.js
    const FetchData = () => {
      // Grab data from useAPI in global context
      const { data, isLoading } = useAPI();
    
      return (
        <div>{!isLoading ? <p>{data[0].category}</p> : <p>Loading...</p>}</div>
      );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 2020-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多