为什么我无法在模态中管理状态以使用Redux打开和关闭?

时间:2018-08-05 19:44:30

标签: javascript reactjs redux react-redux

我希望当用户单击下面Checkout组件内部的<CheckoutButton/>时出现模态。

相反,正在发生的情况是该模式在重新加载我的浏览器时出现,这与我想要发生的情况相反。 List.js文件和/或reducer.js

中我在做什么错

这是我的List.js文件:

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

import FoodButton from '../FoodButtons/FoodButton';

class List extends Component {
    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.props.openModalRedux()}>
                    <button onClick={this.closeModal}>Close</button>
                </Modal>
            </Aux>
        );
    }
}

const mapStateToProps = state => {
    return {
        mClose: state.mClose.closed
    }
};

const mapDispatchToProps = dispatch => {
    return {
        openModalRedux: () => dispatch({type: OPEN_MODAL})
    }
};

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

这是我的reducer.js文件:

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

const initialState = {
    isActive: false
};

const modalOpen = (state = initialState, action) => {
    switch(action.type) {
        case actionTypes.OPEN_MODAL:
            return {
                ...state
            }

        default:
            return state;
    }
};

export default modalOpen;

这里是CheckoutButton.js

import React from 'react';
import Aux from '../../../../hoc/Aux';

const checkoutButton = (props) => (
    <Aux>
        <button onClick={props.clicked}>Checkout</button>
    </Aux>
);

export default checkoutButton;

1 个答案:

答案 0 :(得分:0)

这就是我看到问题的方式。只需提供带有redux适当值的react-modal isOpen属性的精确绑定即可。

列出渲染方法

<Modal isOpen={this.props.isOpen}>
    ...
</Modal>

列出mapStateToProps

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

Reducer(全局)

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