简体   繁体   English

尽管状态发生了变化,但反应不会重新渲染

[英]React not re-rendering despite state being changed

I have a parent component, App.js that contains some state and functions which it passes to its children through properties.我有一个父组件App.js ,其中包含一些状态和函数,它通过属性传递给它的子级。 One of these state values contained within App is a name , which is set whenever the User's access token is successfully verified. App 中包含的这些状态值之一是name ,只要成功验证了用户的访问令牌,就会设置它。

name is passed to a child component, TopBar as a property: name作为属性传递给子组件TopBar

<div className="App">
    <Topbar name={this.state.name} isLoggedIn={this.isLoggedIn}></Topbar>
</div>

App.isLoggedIn() checks document.cookie for a JsonWebToken, verifies it, and updates App state to set the value of name . App.isLoggedIn()检查document.cookie中的 JsonWebToken,对其进行验证,并更新App状态以设置name的值。 isLoggedIn() is called from the child component TopBar like so: isLoggedIn()从子组件 TopBar 调用,如下所示:

class TopBar extends React.Component {
    constructor( props ) {
        super( props );
        [ ... ]
    }

    [ ... ]
    // This is the issue I believe, but I can't think of an alternative
    async componentDidMount() {
        let result = await this.props.isLoggedIn();
        this.setState({'login' : result});
    }

    render() {
return (
    { this.state.login &&
        <li className="nav-item">Welcome <a href="#account">{this.props.name}</a> | <a href="">Logout</a></li>
    }
    {!this.state.login &&
        <li className="navItem"><a href="#login" onClick={this.showModal}>Sign In</a></li>
    }
);

Problem being, when isLoggedIn() is called, the name property does change, however nothing re-renders until a reload of the webpage.问题是,当 isLoggedIn() 被调用时, name属性确实发生了变化,但是在重新加载网页之前不会重新渲染。 Using react dev tools I can see that the proper name value is getting into TopBar as a property.使用反应开发工具,我可以看到正确的name值作为属性进入TopBar

I understand that changing properties shouldn't trigger a re-render, but the properties are state in the parent component, so surely changing their values should trigger a re-render of the entire application?我知道更改属性不应该触发重新渲染,但是属性父组件中的状态,所以更改它们的值肯定会触发整个应用程序的重新渲染吗?

Instead of making componentDidMount async you can outsource your code into a helper function您可以将代码外包到辅助函数中,而不是使 componentDidMount 异步


async checkIfUserIsLoggedIn() {
     let result = await this.props.isLoggedIn();
     this.setState({'login' : result});
}

componentDidMount() {
     checkIfUserIsLoggedIn()
}

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

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