javascript - React TypeError:使用 Context API 时未定义 Object(...)(...)
问题描述
一直在使用 react context api 来尝试在 material-ui 组件之间传递数据。
所以我正在尝试使用材料 ui stepper 提交注册数据。
我将尝试通过指向当前代码和屏幕截图的链接来复制我想要实现的目标
我使用了材料 ui stepper 并说明了我想要传递的道具,如代码链接中所示 - > https://pastebin.com/uu5j6ADB
我独立创建了两个表单,它们在注册期间从用户那里收集数据,即链接中显示的BusinessRegisterForm ( https://pastebin.com/sdFGBfmq ) 和UserRegisterForm ( https://pastebin.com/GbcmByF2 )。
我在两个表单所在的文件夹中创建了一个index.js文件,导入表单并将它们传递给材料 UI 步进器组件,如链接所示( https://pastebin.com/GM9EcVvy)
最后,我创建了一个上下文,以便能够管理在两种表单之间传递的数据的状态,即AuthStepperContext,如图所示(https://pastebin.com/TP7MSJ7Q)我将提供程序传递给根目录下的主 index.js 文件(https: //pastebin.com/f5GFKHC8 )
上面解释了我的项目的结构。
问题
在表单步进器的最后一步,我想提交表单中的数据。在用户输入所有数据后,我将句柄提交函数从道具传递到步进器中的最后一个按钮。为步进器参考此代码(https://pastebin.com/uu5j6ADB)
问题出现在我在 index.js 文件中调用AuthStepperContext的地方,该文件将两种形式传递给材料 ui stepper 。我想从上下文中获取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 函数并将其作为道具传递给 Stepper 时,如图所示(https://pastebin.com/63HXPJkk),我收到错误TypeError: Object(...)(...)未定义
我首先认为错误是由于使用对象作为初始状态并且必须用自己的状态替换每个字段。
当用户想要提交表单数据时,有没有办法捕获数据并在最后一个表单中提交数据?
解决方案
因此,我为可能再次遇到相同问题的任何人找出了问题。问题在于我导入我的一个命名模块的方式。它应该被包裹在花括号中。
类似的帖子中提供了类似的解决方案,这里useContext() 返回未定义
这是我重构代码以将更改应用于步进器后代码中的行:
import {AuthStepperContext} from '../../../Context/AuthStepperContext';
推荐阅读
- java - 使用 Jsoup 删除不包含自己文本的节点
- android - 房间查询 BETWEEN 日期不返回结果
- flutter - 使用 Flutter 加载非常简单的图像非常慢
- sql-server - Azure 数据工厂 - 在查询中引用查找活动
- javascript - 验证 html 中的特定隐藏输入字段是否为空
- firebase - Firestore - 意外读取
- java - 将LibGdx项目导入java后出现错误
- drupal - 使用 Drush 更新 Drupal Core 说它更新成功但没有?
- javascript - 无法从 jquery/javascript 调用 ahref
- laravel - 当数据透视表具有唯一字段时更新 Laravel 数据透视表