wo99999
wo99999

Reputation: 55

React native redux dispatch action

I am new to react redux, i am trying to dispatch an action from a connected component, but i don't know why the action was not able to reach the reducer.

==========================================================================================================

Below are part of my code

app.js

import React, {Component} from 'react';
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import * as reducers from '../reducers';
import CounterApp from './counterApp';

const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
const reducer = combineReducers(reducers);
const store = createStoreWithMiddleware(reducer);

export default class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <CounterApp />
      </Provider>
    );
  }
}

CounterApp.js

class CounterApp extends Component {

  constructor(props) {
    super(props);
  }

  render() {
    const { state, actions } = this.props;
    return (
      <RequestScreen
        counter={state.count}
        {...actions} />
    );
  }
}

export default connect(state => ({
    state: state.counter
  }),
  (dispatch) => ({
    actions: bindActionCreators(counterActions, dispatch)
  })
)(CounterApp);

RequestScreen

export class RequestScreen extends Component {
  constructor(props){
    super(props);
  }

  componentDidMount() {
  } 

  render() {
    const { state, actions } = this.props;

    return (
      <View>
        <TouchableOpacity onPress={() => this.props.increment)}>
          <Text>up</Text>
        </TouchableOpacity>

        <Text>123</Text>
        <Text>{state.count}</Text>
      </View>
    );
  }
}

const mapStateToProps = state => ({
  state: state.counter
})

const mapDispatchToProps = (dispatch) => ({
  increment: () => { dispatch({ type: 'INCREMENT' }) },
  decrement: () => { dispatch({ type: 'DECREMENT' }) },
  reset: () => { dispatch({ type: 'RESET' }) },
})

export default connect(mapStateToProps, mapDispatchToProps)(RequestScreen)

Upvotes: 1

Views: 12339

Answers (1)

Rob Hogan
Rob Hogan

Reputation: 2624

Just a small mistake on this line I think:

<TouchableOpacity onPress={() => this.props.increment)}>

You'll want to be calling that increment function within your handler:

<TouchableOpacity onPress={() => this.props.increment()}>

Or just passing it through directly

<TouchableOpacity onPress={this.props.increment}>

Upvotes: 3

Related Questions