gpt4 book ai didi

javascript - 每当我尝试使用 useContext Hook 使用分派(dispatch)时,我都会收到 "Uncaught TypeError: dispatch is not a function"

转载 作者:行者123 更新时间:2023-12-01 22:52:12 25 4
gpt4 key购买 nike

所以我一直在学习将 useContext 和 useReducer 钩子(Hook)与 action/dispatch 结合使用,每当我尝试从任何组件使用 dipatch 函数时,它都会抛出“Uncaught TypeError: dispatch is not a function”错误。已经 5 次了现在天数:/

我尝试在组件内部以下列方式访问调度函数

// context
import { ModalContext } from "../Context/Contexts/ModalContext";
import { OPEN_IMAGE_MODAL } from "../Context/action.types";

const { dispatch } = useContext(ModalContext);

dispatch({
type: OPEN_IMAGE_MODAL,
payload: { isEnabled: true, imageDetails: { url: doc.url } },
});

这是引用文件

App.js

import React from "react";

// components
import Nav from "./Components/Nav";
import ImageUploadForm from "./Components/ImageUploadForm";
import ImageGrid from "./Components/ImageGrid";

// context
import { ModalContextProvider } from "./Context/Contexts/ModalContext";

const App = () => {

return (
<div className="App">
<Nav />
<ImageUploadForm />
<ModalContextProvider>
<ImageGrid/>
</ModalContextProvider>
</div>
);
};

export default App;

ModalContext.js(上下文和上下文提供程序创建)

import { createContext, useReducer } from "react";

// reducer
import { modalReducer } from "../Reducers/modalReducer";

// components
import ImageModal from "../../Components/ImageModal";

// creating and exporting context
export const ModalContext = createContext();

const initialState = { isEnabled: false, imageDetails: {} };

export const ModalContextProvider = ({ children }) => {
// for selected/clicked image
const [isEnabled, imageDetails, dispatch] = useReducer(
modalReducer,
initialState
);

return (
<ModalContext.Provider value={{ isEnabled, imageDetails, dispatch }}>
{children}
{isEnabled && <ImageModal />}
</ModalContext.Provider>
);
};

modalReducer.js( reducer fn)

import { OPEN_IMAGE_MODAL, CLOSE_IMAGE_MODAL } from "../action.types";

export const modalReducer = (state, action) => {
switch (action.type) {
case OPEN_IMAGE_MODAL:
return {
...state,
isEnabled: true,
imageDetails: action.payload.imageDetails,
};
case CLOSE_IMAGE_MODAL:
return { ...state, isEnabled: false, imageDetails: {} };
default:
return { ...state };
}
};

最佳答案

useReducer返回一个恰好有两个值的数组。您假设有一些第三个值 dispatch,它实际上是 undefinedundefined 不是一个函数。

根据您要使用上下文传递多少值,您可以解决此问题。我喜欢只传递两个值,一个状态和一个调度。

const [state, dispatch] = useReducer(
modalReducer,
initialState
);

return (
<ModalContext.Provider value={{ state, dispatch }}>
{children}
{state.isEnabled && <ImageModal />}
</ModalContext.Provider>
);

在 child 中,只需提取你是怎么做的:

const { dispatch } = useContext(ModalContext);

关于javascript - 每当我尝试使用 useContext Hook 使用分派(dispatch)时,我都会收到 "Uncaught TypeError: dispatch is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74131078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com