首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React-Hooks:在ContextAPI中未定义“Alert”

React-Hooks:在ContextAPI中未定义“Alert”
EN

Stack Overflow用户
提问于 2020-07-08 23:00:37
回答 2查看 143关注 0票数 0

我正在尝试创建用于搜索电影的React应用程序(我正在使用电影数据库API),当我点击搜索按钮时,如果输入为空,我希望弹出一个警报组件,但是我在同一组件中收到警报是未定义的错误。

Alert.js

代码语言:javascript
复制
import React, { useContext } from "react";
import AlertContext from "../context/alert/alertContext";

const Alert = () => {
  const alertContext = useContext(AlertContext);

  const { alert } = alertContext;

  return (
    alert !== null && (
      <div className={`w-full bg-${alert.type} px-4 py-2 rounded`}>
        <p className="text-white text-center font-mono">{alert.msg}</p>
      </div>
    )
  );
};

export default Alert;

GitHub存储库:

https://github.com/Ivan3628/find-movie

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-07-08 23:32:33

看起来你是在把state.alert传递给你的上下文提供者,而实际上你只需要传递state。或者,您需要在缩减程序中定义alert属性。

See here

在AlertState.js中,不是这样:

代码语言:javascript
复制
      value={{
        alert: state.alert,
        setAlert
      }}
    >
      {props.children}
    </AlertContext.Provider>

执行以下操作:

代码语言:javascript
复制
      value={{
        alert: state,
        setAlert
      }}
    >
      {props.children}
    </AlertContext.Provider>
票数 0
EN

Stack Overflow用户

发布于 2020-07-08 23:32:54

考虑这样写:

代码语言:javascript
复制
import React from 'react';
import AlertContext from '../context/alert/AlertContext';

export default function Alert() {

const {alert} = useContext(AlertContext);

if (alert !== null){
    return(
      <div className={`w-full bg-${alert.type} px-4 py-2 rounded`}>
        <p className="text-white text-center font-mono">{alert.msg}</p>
      </div>
    );
}else{
    return;
}

}

如果这不起作用,我建议您使用状态在应用程序中显示一个警告。

代码语言:javascript
复制
//this is a simplified example and may need to be changed based in context.
//in your applicaiton's state:

   this.state = {
     // the rest of your state here
     alertVisibility: false,
     alert: {
        msg: //message goes here,
        type: //type goes here
     }

   }

<div className="alert">
{this.state.alertVisible && <Alert alert={this.state.alert}>}
</div>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62797764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档