【发布时间】:2023-03-06 23:14:01
【问题描述】:
我有一个可以工作的 React 应用程序,包括警报功能,但是当我尝试为生产环境编译时,它会抛出一个类型错误。
我在下面包含了我的警报缩减器、操作和组件的代码:
减速器
import { SET_ALERT, REMOVE_ALERT } from '../actions/types';
const initialState = [{}];
export default function(state = initialState, action) {
const { type, payload } = action;
const merged = { ...initialState, ...state };
switch (type) {
case SET_ALERT:
return [...state, payload];
case REMOVE_ALERT:
return merged.filter(alert => alert.id !== payload);
default:
return state;
}
}
动作
import uuid from 'uuid';
import { SET_ALERT, REMOVE_ALERT } from './types';
export const setAlert = (msg, alertType, timeout = 5000) => dispatch => {
const id = uuid.v4();
dispatch({
type: SET_ALERT,
payload: { msg, alertType, id }
});
setTimeout(() => dispatch({ type: REMOVE_ALERT, payload: id }), timeout);
};
组件
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
const Alert = ({ alerts }) =>
alerts !== null &&
alerts.length > 1 &&
alerts.slice(1).map(alert => (
<div key='alert.id' className={`alert alert-${alert.alertType}`}>
{alert.msg}
</div>
));
Alert.propTypes = {
alerts: PropTypes.array.isRequired
};
const mapStateToProps = state => ({
alerts: state.alert
});
export default connect(mapStateToProps)(Alert);
错误信息是:
./src/reducers/alert.js
TypeError: Cannot read property 'name' of null
at Array.filter (<anonymous>)
【问题讨论】:
-
{ ...initialState, ...state }应该是[ ...initialState, ...state ],但也总是会在开头放置一个空对象。 -
.filter不会改变原始数组,所以merged在这里没用。 -
我删除了 merge 并像以前一样直接调用 state.filter ,但这并没有真正改变任何东西;我仍然有原来的问题。有什么方法可以检查 null 并进行相应的处理吗?
-
在你的reducer代码中,似乎
merged被定义为一个对象,但是你在它上面使用filter方法,对象不存在。发布代码时可能有错字?另外,这是 src/reducers/alert.js 文件的完整代码吗?通过TypeError: Cannot read property 'name' of null,您似乎正在尝试在某处读取name属性,这在您的代码中不会发生。 -
我最后删除了合并,只是过滤了状态。减速器的完整代码是我发布的。我检查了每个调用 setAlert 的文件,但在任何地方都找不到它引用名称。这种方式有什么解决方法吗?
标签: javascript arrays reactjs redux properties