使用redux

时间:2018-05-14 06:12:42

标签: javascript reactjs redux

我试图找出自己如何将键值传递给reducer但没有成功。我的目的是在按钮上编辑所选元素。现在我无法捕捉到元素的id,所有元素都在变化。有人能告诉我它是如何运作的吗?

我的代码在这里: 对于容器:

const mapDispatchToProps = dispatch => {
  return {
    onEditComponent: (component, id) => dispatch({type: actionTypes.EDIT_COMPONENT, data: {componentToReducer: component, ind: id}})
  }
}

和减速器:

case actionTypes.EDIT_COMPONENT:
      return {
       ...state,
       components: state.components.map((component,i) =>  i === action.data.ind ?
       {...component, co: action.data.componentToReducer} : component
     )
    };

当我构建结构html时还有一个代码:

  render() {
    const edit =  this.props.compons.map((comp, index) =>(
        <div
        key={comp.id}>
          <EditComponent
            clicked={this.props.onEditComponent}/>
        </div>
      ));

    return (
      <div>
        <AddComponent
          click={this.props.onAddComponent}
        />

          {
            this.props.compons.map((component)=>(
          <div key={component.id}
          >
            <p
            onClick={this.showTrue}
            className={classes.Component}>{component.co}
            </p>
            <button
            onClick={()=>this.props.onDeleteComponent(component.id)}>
              Delete component
            </button>
          </div>
            ))
          }
          {this.state.show ? edit : null}

      </div>
    )
  }

2 个答案:

答案 0 :(得分:0)

您没有将id和组件传递给onEditComponent操作,将其传递给EditComponent

const edit =  this.props.compons.map((comp, index) =>(
    <div
    key={comp.id}>
      <EditComponent
        comp ={comp}
        clicked={this.props.onEditComponent}/>
    </div>
  ));

并在EditComponent内部单击编辑时,您将编写

handleClick= () => {
   this.props.clicked(this.props.comp, this.props.comp.id)
}

答案 1 :(得分:0)

所以,我有一个解决方案。 EditComponent必须与状态下的reducer(mapStateToProps)连接,然后我可以将它传递给此reducer以调度操作,最后从列表中编辑元素。感谢您的关注。 :)