2017-03-09 58 views
1

私はReduxを新しく導入しました。これが正しい方法であるかどうかを知りたいと思います。同じボタンでサイドバーを開きます。サイドバーをReduxで拡大/縮小する

bool変数がisCollapsedのReactコンポーネントのサイドバーがあります。初期状態はfalseでサイドバーが展開されています。

constructor(props){ 
    super(props) 

    this.state = { 
     sidebar: { isCollapsed: false } 
    } 

    this.onClickCollapseSidebar = this.onClickCollapseSidebar.bind(this) 
} 

そしてonClickに、私はonClickCollapseSidebar

<a onClick={this.onClickCollapseSidebar} className="sidebar-control"></a> 

selfdefinedメソッドを呼び出す午前onClickCollapseSidebarの内側に、私はcollpaseのアクションを派遣し、拡大しています。

onClickCollapseSidebar(event) { 
    if(this.props.sidebar.isCollapsed) { 
     this.props.actions.expandSidebar(this.props.sidebar) 
    } else { 
     this.props.actions.collapseSidebar(this.state.sidebar) 
    } 
} 

そして、これがReduxでこうした状況をどのように処理するのが正しいアプローチかどうかを知りたいと思います。

私は、反応のsetStateメソッドでローカル状態を使用することができますか、それらの状況を処理するにはredux-uiとしてライブラリを使用することができますが、私はreduxのみでそれをやりたいと思います。

それらのアクションのための私の減速がReduxのは、サイドバーの状態を維持するので、あなたは、コンストラクタの状態を宣言する必要はありません

export default function sidebarReducer(state = [], action) { 
switch (action.type) { 
    case types.COLLAPSE_SIDEBAR: 
     return Object.assign({}, state, {isCollapsed: true}) 
    case types.EXPAND_SIDEBAR: 
     return Object.assign({}, state, {isCollapsed: false}) 
    default: 
     return state 
} 
} 

答えて

1

です:

constructor(props){ 
    super(props) 

    this.onClickCollapseSidebar = this.onClickCollapseSidebar.bind(this) 
} 

あなたドンレデューサーはペイロードではなくアクションタイプを使用するため、expandSidebar()collapseSidebar()アクションクリエイターに何かを渡す必要があります。

onClickCollapseSidebar(event) { 
    if(this.props.sidebar.isCollapsed) { 
     this.props.actions.expandSidebar() 
    } else { 
     this.props.actions.collapseSidebar() 
    } 
} 

正しく初期状態を定義します - state = {isCollapsed: false}

export default function sidebarReducer(state = {isCollapsed: false}, action) { 
switch (action.type) { 
    case types.COLLAPSE_SIDEBAR: 
     return Object.assign({}, state, {isCollapsed: true}) 
    case types.EXPAND_SIDEBAR: 
     return Object.assign({}, state, {isCollapsed: false}) 
    default: 
     return state 
} 
} 
+0

をそれは意味を成していただきありがとうございます。 – Enerikes

関連する問題