首页 > 解决方案 > React/Redux 组件未更新

问题描述

我是使用 Redux 的新手,无法弄清楚为什么我的侧边栏组件没有更新以打开抽屉。我可以看到我的操作被调用,但它似乎没有触发我的组件中的任何更新。我试图遵循 Redux 文档,但我看不到我缺少什么,因为我以相同的方式设置了我的代码。

我不想用代码填充帖子,但如果您需要更多信息来帮助解决这个问题,请告诉我。我会很感激任何帮助,谢谢。

解决方案:我在状态对象上使用了错误的属性,所以我的组件没有被更新。它应该是 state.Sidebar.open 而不是 state.open。

const mapStateToProps = (state:any) => ({  
    open: state.Sidebar.open
});

菜单容器:

import { connect } from 'react-redux';
import { toggleSidebar } from '../actions';
import Menu from '../components/Menu/Menu';

const mapStateToProps = (state:any) => ({  
    open: state.open ? state.open : false
});

const mapDispatchToProps = (dispatch:any) => ({
  toggleSidebar: (open:boolean) => dispatch(toggleSidebar(open))
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Menu);

菜单组件:

class Menu extends React.Component<IMenuProps> { 
    private handleDrawerOpen = () => {        
        this.props.toggleSidebar(true);
    }

    private handleDrawerClose = () => {
        this.props.toggleSidebar(false);
    }

    public render() {
        return (
            <div>
                <MenuBar 
                    handleDrawerOpen={this.handleDrawerOpen}
                />
                <SideBar
                    open={this.props.open} 
                    handleDrawerClose={this.handleDrawerClose}
                />
            </div>
        );
    }
}

侧边栏:

class Sidebar extends React.Component<ISideBarProps> {
  public render() {
    return (
      <div>
        <Drawer 
          open={this.props.open} 
          onClose={this.props.handleDrawerClose}>

          <div
            tabIndex={0}
            role="button"
          >
            <AdministrationItems />
          </div>
        </Drawer>
      </div>
    );
  }
}

*编辑减速器:

const sidebar = (state = { open: false }, action:any) => {  
  switch (action.type) {
    case TOGGLE_SIDEBAR: {       
      return {
        open: action.open
      };
    }

    default: {
      return state;
    }
  }
};

行动:

export const toggleSidebar = (open:boolean) => ({
    open,
    type: TOGGLE_SIDEBAR,    
});

标签: javascriptreactjstypescriptredux

解决方案


解决方案:我在状态对象上使用了错误的属性,所以我的组件没有被更新。它应该是 state.Sidebar.open 而不是 state.open。

const mapStateToProps = (state:any) => ({  
    open: state.Sidebar.open
});

推荐阅读