如何订阅组件以进行状态更改?

时间:2019-11-30 09:31:33

标签: reactjs react-redux

当我在分派的容器动作中按按钮并且状态中的道具更改时,但模态组件未显示。如何解决?

容器

const handleOpen = () => {
    dispatch({ type: OPEN_FORM });
}

return (
    <div>
        <FormDialog />
        <button onClick={handleOpen}>Open</button>
    </div>
)

我使用connect()方法将状态置于Modal中。但是当它改变时,什么也没发生

模式

class FormDialog extends React.Component {
    constructor(props) {
        ...some code
        this.state = {
            open: false
        }
    }

    render() {
        const { open } = this.state;
        return (
            <Dialog open={open}>
                ...some code
            </Dialog>
        )
    }
}

const putStateToProps = state => {
    return {
        open: state.uiState.openFormDialog
    }
}

export default connect(putStateToProps)(FormDialog);

解决方案

const FormDialog = props => {
    const { open, dispatch } = props;
    return (
            <Dialog open={open}>
                ...some code
            </Dialog>
    )
}

const putStateToProps = state => {
    return {
        open: state.uiState.openFormDialog
    }
}

export default connect(putStateToProps)(FormDialog);

0 个答案:

没有答案