Ad

React + Redux. Executes All Method/actions Defined In Container And Dump Components

- 1 answer

i'm faced with strange situatuion when all methods, defined in dump component and in container are executed. this is components: Container:

    import React,{Component, PropTypes} from 'react';
import { connect , Provider} from 'react-redux'
import { toggleMenu } from '../actions/'
import Menu from '../components/Menu'


function mapStateToProps (state) {
  var isOpenMenu = state.pageReducer.isOpenMenu != undefined ? state.pageReducer.isOpenMenu: true;
  return {isOpenMenu}
}
function mapDispatchToProps(dispatch) {
  return {
    toggleMenuFactory :  dispatch(toggleMenu())
  }
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Menu);

Component:

import React, { PropTypes, Component } from 'react'
import { Link } from 'react-router'
import { connect } from 'react-redux'
import MenuListItem from './MenuListItem'

import LeftNav from 'material-ui/lib/left-nav';
import RaisedButton from 'material-ui/lib/raised-button';
import MenuItem from 'material-ui/lib/menus/menu-item';


const menuItems = [
  { text: 'Petr Klimenko', link: '' },
  { text: 'developer', link: '' },
  { text: 'Env diff', link: '/envdiff' },
  { text: 'Export to Env', link: '/envexport' }
]

export default class Menu extends Component {

tapMenu () {
   // const {toggleMenu} = this.props;
   console.log(this.props)
}
  render () {

    return (
      <div id="menu" ref="menu" className={this.props.activeClass}>

          <LeftNav open={ this.props.isOpenMenu}>
            <ul>
              <MenuItem> <Link to="/">RocketSibel</Link></MenuItem>
              {menuItems.map((item, i) => <MenuListItem {...item} key={i} />)}
              <RaisedButton label="Toggle Menu"  onTouchTap={this.tapMenu()} />
            </ul>
          </LeftNav >

      </div>
    )
  }
}

in console i see, that method toggleMenu executed when page is rendering, and method tapMenu also executed. I dont know why it happens

Ad

Answer

First problem is that you are not passing function to event handler, but you are calling it. Just change:

onTouchTap={this.tapMenu()}

to:

onTouchTap={this.tapMenu.bind(this)}

Second problem is that connect and mapDispatchToProps has different api. It should be an function which bind action creators, try to change:

function mapDispatchToProps(dispatch) {
  return {
    toggleMenuFactory: dispatch(toggleMenu()) // this executes dispatch function
  }
};

to:

function mapDispatchToProps(dispatch) {
  return {
    toggleMenuFactory: () => dispatch(toggleMenu()) // provide wrapped function (action creator)
  }
};
Ad
source: stackoverflow.com
Ad