简体   繁体   English

Safari 中的状态更改后,React 组件不会重新渲染

[英]React component doesn't rerender after state change in Safari

In my React app build in Gatsby I have form with following fragment of code:在我在 Gatsby 中构建的 React 应用程序中,我有以下代码片段的形式:

<label id="politykaModal" onClick={e => this.handleChangeRatio(e)}>
     <button id="politykaModal" name="polityka-prywatnosci" className={this.state.politykaModalError ? "redBorder" : ""}>
           <div id="politykaModal" className={this.state.politykaModal ? "checked" : ""}/>
     </button>
     Accept privacy policy
</label>

When the user click on the label, it's suppose to change class of inner div for .checked (change background color of inner div).当用户单击标签时,假设将内部 div 的类更改为.checked (更改内部 div 的背景颜色)。 It all works fine in all browsers except for Safari.除了 Safari,它在所有浏览器中都能正常工作。

Here's my handleChangeRatio() method:这是我的handleChangeRatio()方法:

handleChangeRatio(e) {
        e.preventDefault();
        let name = e.target.id;

        if(name === "politykaModal") {
            this.setState((prevState) => {
                return ({
                    politykaModal: !prevState.politykaModal
                });
            });
        }
    }

What's interesting is that state is changing as it should, but the class doesn't (background color of inner div remains the same).有趣的是状态正在发生变化,但类没有(内部 div 的背景颜色保持不变)。 Maybe the problem is with re-rendering the component but then why it works fine in other browsers?也许问题在于重新渲染组件,但为什么它在其他浏览器中工作正常?

Thanks in advance.提前致谢。

I think you don't need to use the prevState , you can just switch between states: Try:我认为您不需要使用prevState ,您可以在状态之间切换:尝试:

    if(name === "politykaModal") {
        this.setState({politykaModal: !this.state.politykalModal)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM