javascript - 为什么上下文未定义
问题描述
问题
我正在尝试通过上下文 API 使警报对话框可重用。但是我收到一个错误,说上下文未定义。我已经定义了我的上下文和对话框组件,如下所示;
const dialogContext = React.createContext();
const {Provider, Consumer} = dialogContext;
const C = {
ask: 'ASK',
}
export function DialogProvider({children}){
const [dialogState, setDialogState] = React.useState({
show: false,
message: '',
type: C.ask,
title: '',
id: '',
})
return(
<Provider value={{dialogState, setDialogState}}>
{children}
</Provider>
)
}
export function AlertDialogSlide({myPayload}) {
const {warn, title, message, callback, id} = myPayload;
const context = React.useContext(dialogContext);
console.log(context, dialogContext);
const {dialogState ,setDialogState} = context;
const open = (id) => {
setDialogState({
...dialogState,
show: true,
message: message.description,
title: message.title,
id,
})
}
if(warn){
open(id)
}
const handleClose = (callBack, args=[]) => {
console.log('arguments',args)
callBack.fn && callBack.fn(...args);
setDialogState({
...dialogState,
show: false,
})
};
return (
<div>
<Dialog
open={dialogState.show}
TransitionComponent={Transition}
keepMounted
onClose={handleClose}
aria-labelledby="alert-dialog-slide-title"
aria-describedby="alert-dialog-slide-description"
>
<DialogTitle id="alert-dialog-slide-title">{title}</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-slide-description">
{message}
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="primary">
No
</Button>
<Button onClick={() => handleClose(callback)} color="primary">
Yes
</Button>
</DialogActions>
</Dialog>
</div>
);
}
使用它我的代码看起来像这样
import {AlertDialogSlide, DialogProvider} from './Dialog';
...
...
<DialogProvider>
<AlertDialogSlide
myPayload={payload}
/>
</DialogProvider>
...
但是,我收到一条错误消息,指出上下文未定义,我无法从上下文中解构所需的值
×
TypeError: Cannot destructure property 'dialogState' of 'context' as it is undefined.
AlertDialogSlide
C:/Users/DESIGNHIVE II/Desktop/sellervasiti/src/components/Dialog.jsx:43
如果在没有整个上下文的情况下有更好的方法来做到这一点,我也希望链接到资源。
解决方案
发现了问题……上面的代码在上下文定义和使用方面是正确的……问题出在代码的其他地方,对话框组件在没有提供程序的情况下使用。感谢大家。
推荐阅读
- asp.net - IIS 不提供任何静态文件
- glog - 如何在一个进程中使用 GLOG 将日志写入不同的日志文件
- python - Python 将日期时间索引(复数索引)转换为多个日期时间范围
- python - 主线程执行时不显示进度指示器
- cmake - CMake add_library 与未来的来源
- sql - Sqlite 连接两个表
- python - ModuleNotFoundError:没有名为“tensorflow.python.keras.applications.MobileNetV2”的模块
- python - 显示列表元素,就好像它们是输入的一样
- javascript - 具有对象的数组 -> 格式化为字符串的数组
- kubernetes - 如何从 Grafana 仪表板中隐藏已终止的 pod