我正在尝试使用ReactJs中的ContextAPI在组件之间共享数据。但是我在使用它时卡住了。这个错误是:
"TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator))"
at
line 7: *const [state, dispatch] = useContext(AppContext);*
这是我的代码。
文件 context.js
import React from "react";
import { useImmer } from "use-immer";
const defaultState = {
feed: [],
listFeed: [],
};
const AppContext = React.createContext();
const AppProvider = ({ children }) => {
const [state, dispatch] = useImmer({ ...defaultState });
return (
<AppContext.Provider value={[state, dispatch]}>
{children}
</AppContext.Provider>
);
};
export { AppProvider, AppContext };
和文件 useContextApp.js
import { useContext} from "react";
import { AppContext } from "./context";
const useAppContext = () => {
const [state, dispatch] = useContext(AppContext);
function updateFeed(feed) {
dispatch((draft) => {
draft.feed = feed;
})
}
function updateListFeed(listFeed) {
dispatch((draft) => {
draft.listFeed = listFeed;
})
}
return {
...state,
updateFeed,
updateListFeed,
};
};
export { useAppContext };
并在主页中使用它。
const { updateFeed} = useAppContext();