使用类时将调度映射到 props



我正在尝试在单击元素时调度 redux 操作。这是我目前设置内容的方式

行动

export function removeItem(idx) {
  // remove the item at idx
  return {
    type: "DESTROY_ITEM",
    payload: {idx: idx}
  }
}

容器组件

import ItemUi from '../ui/Item';
import { connect } from 'react-redux'
import { removeItem } from '../../actions'
const mapDispatchToProps = dispatch => {
  return({
    destroyItem: (index) => {
      dispatch(
        removeItem(index)
      )
    }
  })
}

export default connect(null, mapDispatchToProps)(ItemUi)

用户界面组件

import React, { Component, PropTypes } from 'react';
class Item extends Component {
  // ... methods removed for length
  render() {
    return (
      <div>
        <span 
          className="btn btn-primary btn-xs glyphicon glyphicon-trash"
          onClick={() => {this.props.destroyItem(this.props.index)}}></span>
      </div>
    )
  }
}
DestroyItem.propTypes = {
    onRemoveItem: PropTypes.func
}
export default Item

顶级组件

import React, { Component } from 'react';
import Item from './Item'
class App extends Component {
    render() {
        return(
            <div className="container">
              <NewItem/>
              <ClearAll/>
              <div className="panel-group" id="accordion">
                {this.props.item.map(this.eachItem)} // <-- renders each item
              </div>
            </div>
        )
    }
}
export default App;

当用户单击 Item ui 组件中显示的 span 元素时,我想触发在组件的 index prop 中传递的destroyItem操作。相反,我收到错误

TypeError: _this2.props.destroyItem is not a function

你能提供一些关于我应该如何做到这一点的指导吗?让我知道我是否可以提供任何其他有用的上下文。

尝试:

const mapDispatchToProps = {
    destroyItem: removeItem
}

最新更新