我如何正确设置减速器?

时间:2018-08-06 11:45:30

标签: javascript reactjs debugging redux react-redux

我正在尝试通过redux切换模态,但由于某种原因,我收到一条错误消息:TypeError: Cannot read property 'isModalOpen' of undefined(指向isOpen: state.global.isModalOpen内的行List.js),这意味着我的根减速器定义不正确。但是我确定我已经在index.js文件中正确定义了它。我在做什么错?如何解决这个问题并正确使用这些操作类型才能使其正常工作?

注意:<Modal/>组件是我安装的npm软件包,不是我自己创建的。

这是我的List.js文件:

import React, { Component } from 'react';
import Aux from '../../../../hoc/Aux';
import { connect } from 'react-redux';
import Modal from 'react-modal';

class List extends Component {
    state = {
       isOpen: false
    }

    componentWillMount() {
        Modal.setAppElement('body');
    }

    toggleModal = () => {
        this.setState({isActive:!this.state.isActive});
    }

    closeModal = () => {
        this.setState({isActive: false});
    }

    render() {
        return (
            <Aux>
                <CheckoutButton clicked={this.toggleModal}/>

                <Modal isOpen={this.state.isOpen}>
                    <button onClick={this.closeModal}>Close</button>
                </Modal>
            </Aux>
        );
    }
}

const mapStateToProps = state => {
    return {
        isOpen: state.global.isModalOpen
    }
};

const mapDispatchToProps = dispatch => {
    return {
        closeModalRedux: () => dispatch({type: CLOSE_MODAL})
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(List);

这是我的reducer.js文件:

import React from 'react';
import * as actionTypes from '../action/NoNameAction';

const initialState = {
    isModalOpen: false
};

const global = (state = initialState, action) => {
    switch(action.type) {
        case actionTypes.OPEN_MODAL:
            return {
                ...state,
                isModalOpen: true,
            }
        case actionTypes.CLOSE_MODAL:
            return {
                ...state,
                isModalOpen: false,
            }
        default:
            return state;
    }
};

export default global;

这是我的index.js文件:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

import { Provider } from 'react-redux';
import { createStore, combineReducers } from 'redux';
import modalOpenReducer from './store/reducer/reducer';

const rootReducer = combineReducers({
    isOpen: modalOpenReducer
});

const store = createStore(rootReducer);

ReactDOM.render(<Provider store={store}><App/></Provider>, document.getElementById('root'));
registerServiceWorker();

1 个答案:

答案 0 :(得分:1)

将化简器文件名更改为global.js,然后在root.js中将其导入为global而不是化简器。并且在组件中,将其更改为this.props.isOpen