I am writing a code to apply a theme using redux. Here is my code:
Actions/index.js
export const CHANGE_THEME = 'CHANGE_THEME';
export const changeTheme = (payload) => {
console.log('payload ' + payload)
return ({
type: CHANGE_THEME,
payload
})}
Reducers/index.js
import { combineReducers } from 'redux'
import themeChangeHandler from './themeChangeHandler'
const rightBarMenuHandler = combineReducers({
themeChangeHandler
})
export default rightBarMenuHandler
themeChangeHandler.js
const themeChangeHandler = (state = 'light', action) => {
console.log('rec action ' + action.type)
switch(action.type) {
case 'CHANGE_THEME':
return action.payload
default:
return state
}
}
export default themeChangeHandler
The event is using Menu/MenuItem
class AppBarRightButtonsMenu extends Component {
constructor(props) {
super(props);
}
onClickButton = (data) => {
this.props.dispatch(changeTheme('dark'))
}
render() {
const {onThemeChange, onLogout, dispatch} = this.props;
var i = 1;
if(NavigationButtonMenu) {
var list = NavigationButtonMenu.map( (menuItem) => {
return <MenuItem key={i++} primaryText={menuItem.name} onClick = {this.onClickButton}/>;
});
return <Menu >{list}</Menu>;
} else {
return <div/>
}
}
}
export default connect()(AppBarRightButtonsMenu);
App.js
const App = ({theme}) => (
<SomeComp
theme={theme}
/>
function mapStateToProps(state) {
console.log('state.themeChangeHandler ' + state.themeChangeHandler)
return {
theme: state.themeChangeHandler === 'dark'?darkBaseTheme:customTheme,
};
}
export default connect(mapStateToProps, null) (App);
Adding store
const store = createStore(reducers)
ReactDOM.render(<Provider store={store}>
<App />
</Provider>, document.getElementById('root'));
registerServiceWorker();
I just get the console logs in the action but not the one in reducer(i get test log of reducer on the bootup). What am I doing wrong?
How do you setup your store? You've "combined" your reducers, but you haven't wired up the store yet.
Once you set this all up, you can access the store state like you do in the
App
component.You can find more information about the
Provider
component in the Redux bindings for React documentation.Once you're comfortable with that, I would suggest going over Dan Abramov's excellent course on idiomatic Redux, which mentions a few tricks you can do with the store and the store state in the first videos.