首页 > 解决方案 > 为什么上下文未定义

问题描述

问题

我正在尝试通过上下文 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

如果在没有整个上下文的情况下有更好的方法来做到这一点,我也希望链接到资源。

标签: javascriptreactjs

解决方案


发现了问题……上面的代码在上下文定义和使用方面是正确的……问题出在代码的其他地方,对话框组件在没有提供程序的情况下使用。感谢大家。


推荐阅读