【发布时间】:2019-10-17 01:02:55
【问题描述】:
我正在尝试读取 alertContext 的 alerts 属性:
TypeError: Cannot read property 'alerts' of undefined
Alerts
D:/connection/client/src/layouts/Alerts.js:6
3 |
4 | const Alerts = () => {
5 | const alertContext = useContext(AlertContext);
> 6 | return (
7 | alertContext.alerts.length > 0 &&
8 | alertContext.alerts.map(alert => (
9 | <div key={alert.id} className={`alert alert-${alert.type}`}>
我的 Alerts.js 文件有问题:
import React, { useContext } from "react";
import AlertContext from "../context/alert/alertContext";
const Alerts = () => {
const alertContext = useContext(AlertContext);
return (
alertContext.alerts.length > 0 &&
alertContext.alerts.map(alert => (
<div key={alert.id} className={`alert alert-${alert.type}`}>
<i className='fas fa-info-circle' />
{alert.msg}
</div>
))
);
};
export default Alerts;
我一直在尝试使用 HOOKS 和上下文 api 来管理状态和其他生命周期的东西。
所有与代码相关的文件都放在“context”下一个名为“alert”的目录中。
以下是其他文件: alertContext.js
import { createContext } from "react";
const alertContext = createContext();
export default alertContext;
AlertState.js
import React, { useReducer } from "react";
import uuid from "uuid";
import AlertContext from "./alertContext.js";
import alertReducer from "./alertReducer.js";
import { SET_ALERT, REMOVE_ALERT } from "../types.js";
const AlertState = props => {
const initialState = [];
const [state, dispatch] = useReducer(alertReducer, initialState);
// SetAlert
const setAlert = (msg, type, timeout = 5000) => {
const id = uuid.v4();
dispatch({
type: SET_ALERT,
payload: { msg, type, id }
});
setTimeout(() => dispatch({ type: REMOVE_ALERT, payload: id }), 5000);
};
return (
<AlertContext.Provider
value={{
// Initial State
alerts: state,
setAlert
}}
>
{props.children}
</AlertContext.Provider>
);
};
export default AlertState;
**alertReducer.js**
import { SET_ALERT, REMOVE_ALERT } from "../types.js";
export default (state, action) => {
switch (action.type) {
case SET_ALERT: {
return [...state, action.payload];
}
case REMOVE_ALERT: {
return state.filter(alert => alert.id !== action.payload);
}
default:
return state;
}
};
【问题讨论】:
-
这只是意味着您的
AlertContext在安装Alerts组件时没有值,因此会出现错误。确保你有一个需要的值或使用条件渲染 -
请确保
AlertState是Alerts的父级。例如<AlertState><Alerts /></AlertState>
标签: reactjs react-context