Hello,
I got a strange problem and I have no idea what causes this.
The approach that I am using is the mapStateToProps / mapDispatchToProps.
The strang thing is:
The logger shows that the state is changed to true but then the reducers gets called again and its set back to false again.
For better understanding, here's the code a code sample.
Action creator:
//../actions/shellActions
import { TOGGLE_SIDEBAR } from '../constants/actionTypes';
export function toggleNavigation() {
return {
type: TOGGLE_SIDEBAR
}
}
Reducer
//../reducers/navigationReducer
import { TOGGLE_SIDEBAR } from '../constants/actionTypes';
export default function toggleSidebar(state:boolean=false, action:any) {
let hideSidebar = !state;
switch (action.type) {
case TOGGLE_SIDEBAR:
return hideSidebar;
default:
return state;
}
}
//../reducers/rootReducer
import { default as toggleSidebar } from './navigationReducer';
const rootReducer: Redux.Reducer = combineReducers({
toggleSidebar: toggleSidebar
});
export default rootReducer;
Container
import * as React from 'react';
import { connect } from 'react-redux';
import { toggleNavigation } from '../actions/shellActions';
class App extends React.Component<any, any> {
constructor(props) {
super(props);
}
onToggle() {
//this.props.toggleNavigation(); This gets called once
this.props.dispatch(toggleNavigation()); // This gets called twice
}
render() {
return (
<div className={ isSidebarVisible ? "body-container" : "body-container sidebar-open"}>
<button onClick={ this.onToggle.bind(this) }>Toggle</button>
</div>
);
}
}
function mapStateToProps(state: RootState):AppProp {
return {
isSidebarVisible: state.toggleSidebar
};
}
function mapDispatchToProps(dispatch) {
const actions: AppProp = {
dispatch: dispatch,
toggleNavigation: toggleNavigation
};
return bindActionCreators(actions, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
Maybe I did something wrong.
Thanks
If you're using bindActionCreators and mapDispatchToProps, the action creators _are already bound_. There is no need to call dispatch() on their return values. The whole point of bindActionCreators() is _not_ to call dispatch(). You should either bindActionCreators() and call them as is, or not use it, and call dispatch().
Thank you for the explanation @gaearon.
Most helpful comment
If you're using
bindActionCreatorsandmapDispatchToProps, the action creators _are already bound_. There is no need to calldispatch()on their return values. The whole point ofbindActionCreators()is _not_ to calldispatch(). You should eitherbindActionCreators()and call them as is, or not use it, and calldispatch().