【问题标题】:Object is undefined when trying to fetch it using useContext()尝试使用 useContext() 获取对象时未定义对象
【发布时间】:2021-12-14 00:34:36
【问题描述】:

我对 React 非常陌生,并试图在 React 中创建一个上下文,以便在我的笔记应用程序中触发我为相关用户活动定制的警报,但是当我尝试使用上下文中的值时useContext 我收到错误消息:“无法解构 'Object(...)(...)' 的属性 'alert',因为它是未定义的。”

这是代码:-

创建上下文

import React from 'react';

const AlertContext = React.createContext(null);

export default AlertContext;

向上下文填充值

import React,{useState} from 'react';
import AlertContext from "./AlertContext";

const ShowAlert = (props)=>{
    const [alert,setAlert] = useState(null);

    const showAlert = (message,type)=>{
            setAlert({
                msg:message,
                type:type
            })
            setTimeout(()=>{
                setAlert(null);
            },3000);
    }

    return(
        <AlertContext.Provider value={{alert,showAlert}}>
            {props.children}
        </AlertContext.Provider>
    )
}

export default ShowAlert;

尝试使用这些值

import React, { useContext } from "react";
import { Navbar, Button, Nav } from "react-bootstrap";
import { Link, useHistory } from "react-router-dom";
import ShowAlert from "../contexts/ShowAlert";
import MyAlert from "./MyAlert";

function Header() {

  const {alert} = useContext(ShowAlert);

  let history = useHistory();

  const handleLogout = () => {
    localStorage.removeItem("token");
    history.push("/login");
  };

  return (
    <>
    <header>
      <Navbar collapseOnSelect expand="lg" className="header">
        <Navbar.Brand className="heading">
          <Link to="/" className="headerLink">
            Note Cloud
          </Link>
          <i className="fas fa-cloud-upload-alt cloudIcon"></i>
        </Navbar.Brand>
        <Navbar.Toggle aria-controls="responsive-navbar-nav" />
        <Navbar.Collapse id="responsive-navbar-nav">
          <Nav className="me-auto"></Nav>
          {localStorage.getItem("token") && (
            <Nav>
              <Nav.Link>
                <Button variant="primary" size="lg" onClick={handleLogout}>
                  Logout
                </Button>
              </Nav.Link>
            </Nav>
          )}
        </Navbar.Collapse>
      </Navbar>
    </header>
   <MyAlert alert={alert}></MyAlert>
    </>
  );
}

export default Header;

编辑:- MyAlert 组件

import React, { useContext } from "react";
import { Alert } from "react-bootstrap";
import ShowAlert from "../contexts/ShowAlert";

const MyAlert = (props) => {
  
  const {alert} = useContext(ShowAlert);
  const capitalize = (word) => {
    if(word==="danger")
    {
      word = "error";
    }
    const lower = word.toLowerCase();
    return lower.charAt(0).toUpperCase() + lower.slice(1);
  };
  return (
    <div style={{ height: "50px" , width:"100%"}}>
      {alert && (
        <Alert
          variant={alert.type}
        >
          <Alert.Heading>{capitalize(alert.type)}</Alert.Heading>
          <p>{capitalize(alert.msg)}</p>
        </Alert>
      )}
    </div>
  );
};

export default MyAlert;

我遇到的错误

【问题讨论】:

  • alert 也是一个浏览器 api 功能,这也可能导致某种问题。使用其他名称,例如 noteAlert。

标签: javascript reactjs use-context react-fullstack


【解决方案1】:

尝试像这样而不是 null。

import React from "react";

const AlertContext = React.createContext({
  alert: {},
  setAlert: (alert) => {},
});

export default 

【讨论】:

  • 感谢您的回复我尝试过这种方式但同样的错误仍然存​​在,我已经添加了我的 MyAlert 组件的代码,如果您可以建议任何其他方式也可以实现这是我的最终目标非常有帮助
【解决方案2】:

我认为你的出口是失败的

export const  AlertContext = React.createContext({})

或者你也可以试试:

< AlertContext.Consumer>
    {(context) => {
      console.log(context)
    }}
  </AlertContext.Consumer>

【讨论】:

  • @m3w 感谢您的回复我尝试了这种方式(第一个通过更正我的导出)但同样的错误仍然存​​在。
  • @m3w 我已经添加了我的 MyAlert 组件的代码,如果您能提出任何其他方法也很有帮助,这是我实现的最终目标
猜你喜欢
  • 2017-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 2020-12-03
  • 2016-05-02
  • 2021-06-25
相关资源
最近更新 更多