![](/img/trans.png)
[英]TypeError: dispatch is not a function when using react-context api
[英]React TypeError: Object(...)(...) is undefined when using Context API
一直在使用反应上下文 api 来尝试在 material-ui 组件之间传递数据。
所以我正在尝试使用材料 ui 步进器提交注册数据。
我将尝试通过指向当前代码和屏幕截图的链接复制我想要实现的目标
我使用了材料 ui 步进器并声明了我想要传递的道具,如代码链接所示 -> https://pastebin.com/uu5j6ADB
我独立创建了两个 forms,它们在注册期间从用户那里收集数据,即链接中显示的BusinessRegisterForm ( https://pastebin.com/sdFGBfmq ) 和UserRegisterForm ( https://pastebin.com/GbcmByF2 )。
我在两个 forms 所在的文件夹中创建了一个index.js文件,导入了 forms 并将它们传递给材质 UI 步进器组件,如链接中所示 ( https://pastebin.com/GM9EcVvy )
最后,我创建了一个上下文,以便能够管理两个 forms 之间传递的数据的 state,即AuthStepperContext ,如图所示( https://pastebin.com/TP7MSJ7Q )我将提供者传递给根目录下的主 index.js 文件( https: //pastebin.com/f5GFKHC8 )
上面解释了我的项目是如何构建的。
问题
在表单步进器的最后一步,我想提交来自 forms 的数据。在用户输入所有数据后,我将句柄 Submit function 从 props 传递到步进器中的最后一个按钮。 为步进器参考此代码( https://pastebin.com/uu5j6ADB )
问题出在我调用 index.js 文件中的AuthStepperContext时,它将两个 forms 传递给材质 ui 步进器。 我想从上下文中获取 handleSubmit 并将其作为道具传递给步进器,并将其作为用户在提交所有数据之前填写的最后一个表格传递给商业注册表格。
import React, { useContext, useState } from 'react';
import BusinessRegisterForm from './BusinessRegisterForm';
import UserRegisterForm from './UserRegisterForm';
import HorizontalStepper from '../../controls/HorizontalOptionalStepper';
import Container from '@material-ui/core/Container';
import AuthStepperContext from '../../../Context/AuthContext';
import axios from 'axios'
import { useAuth } from '../../../Context/AuthContext'
export default function RegisterStepper() {
// the issue happens when i introduce this context
// and try to pass it down to the stepper
const {handleSubmit} = useContext(AuthStepperContext)
const getSteps = () => {
return ['Create Account', 'Add Business'];
}
const getStepContent = (step) => {
switch (step) {
case 0:
return <UserRegisterForm />;
case 1:
return <BusinessRegisterForm />;
default:
return 'Unknown step';
}
}
const isStepOptional = (step) => {
return ;
}
const [activeStep, setActiveStep] = useState(0);
return (
<Container maxWidth='sm'>
<HorizontalStepper
getSteps = {getSteps}
getStepContent = {getStepContent}
isStepOptional = {isStepOptional}
activeStep = {activeStep}
setActiveStep = {setActiveStep}
handleSubmit = {handleSubmit}
/>
</Container>
)
}
当我从 Context 调用 handleSubmit function 并将其作为道具传递给 Stepper 时,如图所示 ( https://pastebin.com/63HXPJkk ),我收到错误TypeError: Object(...)(...)未定义
我首先认为错误是由于使用对象作为初始 state 并且不得不用它自己的 state 替换每个字段。
当用户要提交表单数据时,有没有办法在最后一个表单中捕获数据并提交数据?
所以我为可能再次遇到同样问题的任何人解决了这个问题。 问题在于我导入命名模块之一的方式。 它应该用花括号包裹。
在此处的类似帖子中提供了类似的解决方案useContext() returns undefined
这是我重构代码以将更改应用到步进器后代码中的一行:
import {AuthStepperContext} from '../../../Context/AuthStepperContext';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.