Reputation: 27
I can't seem to figure out why I can't update the counter even tho I'm dispatching the correct action type and they fall within the INCREMENT and DECREMENT states. I tried passing a mapDispatchToProps and putting functions within that function and I still get the same problem, nothing updates the state for some reason.
Index:
import {createStore} from 'redux';
import {Provider} from 'react-redux';
import {reducer} from './src/reducers/counter';
const store = createStore(reducer);
const Main = () => (
<Provider store={store}>
<App />
</Provider>
);
AppRegistry.registerComponent(appName, () => Main);
App
import {connect} from 'react-redux';
// create a component
class App extends Component {
increment = () => {
this.props.dispatch({type: 'INCREMENT'});
};
decrement = () => {
this.props.dispatch({type: 'DECREMENT'});
};
render() {
return (
<View style={styles.container}>
<Button onClick={this.increment} title={'Add 1'} />
<Text>Counter {this.props.count} </Text>
<Button onClick={this.decrement} title={'Subtract 1'} />
</View>
);
}
}
Counter
const initState = {
count: 1,
};
export const reducer = (state = initState, action) => {
switch (action.type) {
case 'INCREMENT':
return {
count: state.count + 1,
};
case 'DECREMENT':
return {
count: state.count - 1,
};
default:
return state;
}
};
Upvotes: 1
Views: 1455
Reputation: 683
You have to connect the App component into the redux store with connect
function.
import { connect } from 'react-redux';
// create a component
class App extends Component {
increment = () => {
this.props.increment();
};
decrement = () => {
this.props.decrement();
};
render() {
return (
<View style={styles.container}>
<Button onPress={this.increment} title={'Add 1'} />
<Text>Counter {this.props.count} </Text>
<Button onPress={this.decrement} title={'Subtract 1'} />
</View>
);
}
}
const mapStateToProps = state => ({ count: state.count })
const mapDispatchToProps = dispatch => {
return {
increment: () => dispatch({ type: 'INCREMENT' }),
decrement: () => dispatch({ type: 'DECREMENT' }),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
Upvotes: 0
Reputation: 16
These point need to be taken care of in order for this to work:
constructor() {
super(props)
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
}
Upvotes: 0
Reputation: 42188
This is React Native app, right? Your error is that you used onClick
for the Button
instead of onPress
. It works fine now after switching that prop name.
Upvotes: 2