我正在尝试创建用于搜索电影的React应用程序(我正在使用电影数据库API),当我点击搜索按钮时,如果输入为空,我希望弹出一个警报组件,但是我在同一组件中收到警报是未定义的错误。
Alert.js
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存储库:
发布于 2020-07-08 23:32:33
看起来你是在把state.alert传递给你的上下文提供者,而实际上你只需要传递state。或者,您需要在缩减程序中定义alert属性。
在AlertState.js中,不是这样:
value={{
alert: state.alert,
setAlert
}}
>
{props.children}
</AlertContext.Provider>执行以下操作:
value={{
alert: state,
setAlert
}}
>
{props.children}
</AlertContext.Provider>发布于 2020-07-08 23:32:54
考虑这样写:
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;
}
}如果这不起作用,我建议您使用状态在应用程序中显示一个警告。
//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>https://stackoverflow.com/questions/62797764
复制相似问题