Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Redux connect API does not inject dispatch property

Tags:

reactjs

redux

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.

like image 925
JustWonder Avatar asked Jan 07 '16 12:01

JustWonder


1 Answers

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.

like image 151
Henrik Andersson Avatar answered Sep 28 '22 14:09

Henrik Andersson