在 React 中重新渲染 AppBar 组件

Re renderling AppBar component in React

我有一个 AppBar 组件,如下所示

<AppBar title="Shopping List App" showMenuIconButton={true}
                    iconElementRight={checkAuthenticationToken()?<Menu/>:null}
                    iconElementLeft={<IconButton><NavigationClose /></IconButton>}
                />

iconElementRight 应该只在 checkAuthenticationToken() 评估为 true 后呈现 Menu 组件,它在登录后执行。但是,它不是,我必须手动刷新浏览器才能显示。我相信这是因为 AppBar 组件没有任何变化,因此不会再次调用其 render 方法。我的问题是如何在成功登录后刷新 AppBar 或全部 ReactDom

ReactDOM.render(
    <Provider store={store}>
        <BrowserRouter>
            <MuiThemeProvider muiTheme={getMuiTheme(muiTheme)}>
                <AppBar title="Shopping List App" showMenuIconButton={true}
                    iconElementRight={checkAuthenticationToken()?<Menu/>:null}
                    iconElementLeft={<IconButton><NavigationClose /></IconButton>}
                />
                <div className="container">
                    <Switch>
                        <Route exact path="/" render={requireLogin}/>
                        <Route path="/login" render={isLoggedIn}/>
                        <Route path="/register" component={RegisterForm}/>
                        <Route path="/shoppinglists" render={requireLogin}/>
                        <Route path="/:id/shoppinglist_items" render={itemsRequireLogin}/>
                        <Route component={NotFound}/>
                    </Switch>
                </div>
            </MuiThemeProvider>
        </BrowserRouter>
    </Provider>
    , document.getElementById('root'));

如果您的组件未连接到 redux 存储,状态更改不会触发新的渲染,因此您不会更新组件。

现在的情况是,它只会在调用 render 方法时执行此检查...

一种可能的解决方案是将您的 AppBar 组件包装到另一个连接到 redux 状态的组件中,因此只要您需要的状态部分在商店中更新,它就会更新

const mapStateToProps = (state, ownProps) {
  const { isAuthenticated } = state.authentication // Get whatever you need from the reducer that handles authentication state
  return { isAuthenticated } 
}

class MyAppBar extends Component {
  ...

  render(){
    return(<AppBar iconElementRight={this.props.isAuthenticated ? <Menu /> : null} {rest of your props})
  }
}

export default connect(mapStateToProps)(MyAppBar)

这样,组件将跟踪与身份验证缩减程序相关的商店上的任何更改,并将触发渲染方法(在需要时执行检查)