代码之家  ›  专栏  ›  技术社区  ›  E_K

在React中重新渲染AppBar组件

  •  0
  • E_K  · 技术社区  · 7 年前

    我有一个 AppBar 组件如下所示

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

    这个 iconElementRight 应仅渲染 Menu 之后的组件 checkAuthenticationToken() 登录后计算为true。但是,它不是,我必须手动刷新浏览器才能显示它。我相信这是因为 导航栏 组件及其 render 方法不会再次调用。我的问题是如何刷新 导航栏 或全部 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'));
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Alexandre Wiechers Vaz    7 年前

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

    按照目前的方式,只有当 render 已调用方法get。。。

    一种可能的解决方案是 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)
    

    这样,组件将跟踪与身份验证缩减器相关的存储上的任何更改,并触发呈现方法(在需要时执行检查)