mapStateToProps connect必须返回一个普通对象

时间:2017-07-24 10:03:03

标签: react-redux

我正在尝试使用Redux打开一个模态,但是,我收到了错误:

Connect(ModalRoot)中的

mapStateToProps()必须返回一个普通对象。取而代之的是未定义的。

这是我的模态组件:

import React from 'react';
import { connect } from 'react-redux';

import InformationModal from './InformationModal.js';

const MODAL_COMPONENTS = {
  SHOW_INFORMATION: InformationModal,
  // ADD_ACHIEVEMENT: AddAchievementModal,
  // SHOW_ERROR: ErrorModal,

  /* other modals */
};

const ModalRoot = ({ modalType, modalProps }) => {
  if (!modalType) {
    return <span />; // after React v15 you can return null here
  }

  const SpecificModal = MODAL_COMPONENTS[modalType];
  return <SpecificModal {...modalProps} />;
};

export default connect(state => state.modal)(ModalRoot);

我的信息模式:

export default class InformationModal extends Component {
  constructor() {
    super();
  }

  render() {
    return (
      <span>
        <ModalWrapper onRequestClose={this.props.onClose} contentLabel={title}>
          <Text>hello</Text>
        </ModalWrapper>
      </span>
    );
  }
}

我的模态包装器:

class ModalExample extends Component {
  state = {
    modalVisible: false,
  };

  setModalVisible(visible) {
    this.setState({ modalVisible: visible });
  }

  render() {
    return (
      <View style={{ marginTop: 22 }}>
        <Modal
          animationType={'slide'}
          transparent={false}
          visible={this.state.modalVisible}
          onRequestClose={() => {
            alert('Modal has been closed.');
          }}>
          {this.props.children}
        </Modal>
      </View>
    );
  }
}

任何人都知道我为什么会收到此错误?

1 个答案:

答案 0 :(得分:2)

在此功能中:

export default connect(state => state.modal)(ModalRoot);

state.modal未定义且mapStateToProps要求您返回对象

试试这个:

export default connect(state => state.modal || {})(ModalRoot);