如何在React中的Array中修复TypeError“无法读取null的属性'x'”

时间:2019-09-13 18:02:37

标签: javascript arrays reactjs redux properties

我有一个可以正常工作的React应用程序,其中包括警报功能,但是当我尝试进行生产编译时会抛出类型错误。

我在下面包括了我的警报减少器,操作和组件的代码:

减速器

onSumResult: console.log(sum)

动作

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);

2 个答案:

答案 0 :(得分:0)

我和你有完全一样的错误,这就是我所做的:

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 { SET_ALERT, REMOVE_ALERT } from "../types";
const initialState = [];

export default function(state = initialState, { type, payload }) {
  switch (type) {
    case SET_ALERT:
      return payload;
    case REMOVE_ALERT:
      return [];
    default:
      return state;
  }
}

并执行一个干净的git init和Voilà,这是我为课程https://github.com/syahmiyani/devlepak

答案 1 :(得分:0)

将您的减速器更改为以下代码。您需要提供函数名称。

import { SET_ALERT, REMOVE_ALERT } from '../actions/types';

const initialState = [{}];

const alert = (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;
  }
};

export default alert;