在CodeSandbox中反应上下文

时间:2020-08-12 18:50:54

标签: reactjs react-hooks react-context codesandbox

我在使用CodeSandbox的React Context遇到问题。

我的基本示例:

App.js

import React, { useEffect, useContext } from "react";
import { FirmsContext } from "./FirmsContext";

export default function App() {
const { firms, fetchFirms } = useContext(FirmsContext);

  useEffect(() => {
   (async function getFirms() {
    await fetchFirms();
   })();
  }, [fetchFirms, firms]);

return (
 <div>
 </div>
);
}

FirmsConext.js

import React, { createContext, useReducer } from "react";
import FirmsReducer from "./FirmsReducer";

// INIT STATE
const initalState = {
 firms: []
};

// CREATE CONTEXT
export const FirmsContext = createContext(initalState);

// PROVIDER COMPONANT
export const FirmsProvider = ({ children }) => {
 const [state, dispatch] = useReducer(FirmsReducer, initalState);

 async function fetchFirms() {
  try {
   let response = await fetch("https://pokeapi.co/api/v2/pokemon-species/");
    dispatch({
     type: "GET_FIRMS",
     payload: response.result
    });
  } catch (err) {
    console.log(err);
   }
 }

return (
  <FirmsContext.Provider
    value={{
      firms: state.firms,
      fetchFirms
    }}
  >
    {children}
  </FirmsContext.Provider>
);
};

FirmsReducer.js

export default (state, action) => {
 switch (action.type) {
  case "GET_FIRMS":
    return {
      ...state,
      loading: false,
      firms: action.payload
    };
  default:
    return state;
 }
};

我收到以下错误: fetchFirms不是函数

这显示在app.js的useEffect钩子上

   9 | 
  10 | useEffect(() => {
  11 |   (async function getFirms() {
> 12 |     await fetchFirms();
     |          ^
  13 |   })();
  14 | }, [fetchFirms, firms]);
  15 | 

我在其他地方也有非常相似的代码,可以很好地工作,所以不确定这是CodeSandbox,还是我只是缺少什么?

1 个答案:

答案 0 :(得分:1)

如果要使用提供程序提供的值,则需要像这样使<App />成为<FirmsProvider />的后代

<FirmsProvider>
  <App />
</FirmsProvider>

否则,您将只看到创建上下文所用的初始值。