JustWonder
JustWonder

Reputation: 2433

React Redux connect API does not inject dispatch property

I use react-redux to connect React with Redux store, and use "connect" API to inject "dispatch" property to the component. But the component does not receive the "dispatch" property. Here is the code to demonstrate the problem I encounter:

"use strict"

var React = require('react');
var ReactDOM = require('react-dom');
var Redux = require('redux');
var ReactRedux = require('react-redux');
var Provider = ReactRedux.Provider;

function menuManager(state = {count: 0}, action) {
  switch (action.type) {
    case 'ADD':
      return state + 1;
    case 'REMOVE':
      return state - 1;
    default:
      return state;
  }
}

let store = Redux.createStore(menuManager);

let TestLab = React.createClass({
  onRemove: function(itemRemove) {
    // this.props.dispatch undefined.
    this.props.dispatch({type: 'REMOVE'});
  },
  onAdd: function() {
    const { dispatch } = this.props
    // this.props.dispatch undefined.
    this.props.dispatch({type: 'ADD'});
  },
  getInitialState: function() {
    return { count: 0 };
  },
  render: function() {
    return (
        <div>
          <p>Total count: { this.state.count }</p>
          <button type="button" onClick={this.onAdd}>Add Item</button>
        </div>
    );
  }
});

function select(state) {
  return state;
}

ReactRedux.connect(select)(TestLab);

var target = document.createElement('div');
document.body.appendChild(target);
ReactDOM.render(<Provider store={store}><TestLab /></Provider>, target);

When I try to call "this.props.dispatch", I get an error that "this.props.dispatch" is not defined.

Upvotes: 5

Views: 3081

Answers (1)

Henrik Andersson
Henrik Andersson

Reputation: 47172

You're not using the connected component, connect() returns a new component.

TestLab = ReactRedux.connect(select)(TestLab);
ReactDOM.render(<Provider store={store}><TestLab /></Provider>, target);

You'll run in to some other issues as well, namely you're using this.state.count instead of this.props.count and your reducer function tries to increment or decrement on an object not the integer inside.

Upvotes: 6

Related Questions