【问题标题】:React state not updating反应状态不更新
【发布时间】:2018-03-28 04:54:03
【问题描述】:

所以我正在制作一个简单的 React 应用程序,它需要在单击某物时显示一个模式。我使用 react-modal 来实现这一点,并且模式正在显示,但我无法再次关闭它。代码如下:

    import React from 'react';
    import ReactDOM from 'react-dom';
    import Paper from "./Paper";

    ReactDOM.render(
        <Paper title={"Title"} notes={"Notes"}/>,
        document.getElementById('root')
    );

以及论文定义:

    import React, {Component} from 'react';
    import Modal from 'react-modal';

    class Paper extends Component {

        constructor(props) {
            super(props);
            this.state = {modalIsOpen: false};
            this.showModal = this.showModal.bind(this);
            this.closeModal = this.closeModal.bind(this);
        }

        showModal() {
            this.setState({modalIsOpen: true});
        }

        closeModal() {
            this.setState({modalIsOpen: false});
        }

        render() {
            return (
                <div onClick={this.showModal}>
                    {this.props.title}
                    <Modal isOpen={this.state.modalIsOpen}>
                        <button onClick={this.closeModal}>close</button>
                        {this.props.notes}
                    </Modal>
                </div>
            );
        }

    }

如果我在开发人员工具中检查状态,状态就不会更新,我不知道为什么。谁能帮帮我?

【问题讨论】:

  • 我看不出代码有什么问题,你有任何控制台错误吗?或许可以在渲染顶部添加一个console.log 以查看this.state.modalIsOpen 的值是什么。

标签: reactjs modal-dialog state


【解决方案1】:

我能够重现您的问题,这实际上有点奇怪 - 即使我在设置为 false 后在 setState 回调中记录了 this.state.modalIsOpen,该值仍然是 true。无论如何,我更改了代码以执行切换并解决了问题:

https://codesandbox.io/s/q38nzl9yy9

toggleModal() {
    this.setState({ modalIsOpen: !this.state.modalIsOpen });
}

render() {
    return (
    <div onClick={this.showModal}>
        {this.props.title}
        <Modal isOpen={this.state.modalIsOpen}>
        <button onClick={this.closeModal}>close</button>
        {this.props.notes}
        </Modal>
    </div>
    );
}

我仍在深入研究为什么 this 上下文似乎变得混乱,因为这似乎是一个简单的示例。

【讨论】:

  • 谢谢你!确实很奇怪...如果您有解释,请告诉我!
  • 哇,为this.setState 编写切换的非常简洁的方式。我一直用三元。非常好!
猜你喜欢
  • 1970-01-01
  • 2021-01-28
  • 2023-04-02
  • 2021-01-17
  • 2020-12-28
  • 2021-01-14
相关资源
最近更新 更多