Reactjs 使用类时将分派映射到道具
我试图在单击元素时发送redux操作。以下是我目前的设置方式 行动 容器组件 ui组件Reactjs 使用类时将分派映射到道具,reactjs,redux,react-redux,Reactjs,Redux,React Redux,我试图在单击元素时发送redux操作。以下是我目前的设置方式 行动 容器组件 ui组件 import React,{Component,PropTypes}来自'React'; 类项扩展组件{ //…删除长度的方法 render(){ 返回( {this.props.destroyItem(this.props.index)}> ) } } DestroyItem.propTypes={ onRemoveItem:PropTypes.func } 导出默认项 顶层组件 import React
import React,{Component,PropTypes}来自'React';
类项扩展组件{
//…删除长度的方法
render(){
返回(
{this.props.destroyItem(this.props.index)}>
)
}
}
DestroyItem.propTypes={
onRemoveItem:PropTypes.func
}
导出默认项
顶层组件
import React,{Component}来自'React';
从“./Item”导入项目
类应用程序扩展组件{
render(){
返回(
{this.props.item.map(this.eachItem)}/试试:
尝试:
你能在Item component中的return语句之前尝试记录this.props吗?你能告诉我们如何呈现“Item”吗在你的应用程序中?@TharakaWijebandara上面显示了项目
的渲染
。@ShubhamKhatri当我记录这个时。不包括道具
销毁项目
。知道为什么不包括吗?你能在项目组件的返回语句之前尝试记录这个.props吗?你能告诉我们如何渲染“项目”吗在你的应用程序中?@TharakaWijebandara上面显示了项目
的渲染
。@ShubhamKhatri,当我记录这个时。不包括道具
销毁项目
。知道为什么不包括吗?这是一个有效的答案,并且是建议的方法。传递一个充满动作创建者的对象会自动将它们绑定到dispatch
,由于原始示例只是将索引
参数直接转发到removietem
,这将产生相同的行为。我强烈建议尽可能对mapDispatch
使用对象速记语法,而不是显式编写mapDispatch
函数。(来源:我是Redux维护者。)@markerikson是正确的。在阅读react Redux文档for connect后,速记优于使用bindActionCreators.Yup。(从技术上讲,对象速记只是在引擎盖下调用bindActionCreators
,与您最初的答案完全相同。)谢谢!我尝试实现此更改,但this.props.destroyItem
是未定义的
。你知道为什么吗?你上面写的代码看起来是正确的,所以你确定要使用操作文件的正确路径导入removeItem
吗?这是一个有效答案,也是建议的方法。传递一个完整的对象of action creators会自动将它们绑定到dispatch
,由于原始示例只是将index
参数直接转发到removietem
,这将产生相同的行为。我强烈建议尽可能使用mapspatch
的对象速记语法,而不是而不是显式编写mapDispatch
函数。(来源:我是Redux维护者。)@markerikson是正确的。在阅读了react Redux文档以进行连接后,速记优于使用bindActionCreators.Yup。(从技术上讲,对象速记只是在引擎盖下调用bindActionCreators
,与您在原始答案中的操作完全相同。)谢谢!我尝试实现此更改,但this.props.destroyItem
未定义。知道原因吗?您上面编写的代码看起来是正确的,因此您确定要使用操作文件的正确路径导入removeItem
?
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;
const mapDispatchToProps = {
destroyItem: removeItem
}