我使用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>
);
}
FirmsNext.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,还是我只是缺少了什么?
如果您想使用提供者提供的值,您需要使<App />
成为<FirmsProvider />
的后代,就像一样
<FirmsProvider>
<App />
</FirmsProvider>
否则,您将只看到创建上下文时使用的初始值。