【问题标题】:React-Redux- Delete an item from listReact-Redux - 从列表中删除一个项目
【发布时间】:2016-08-28 19:40:39
【问题描述】:

目前我正在从事这个 FCC 项目: https://www.freecodecamp.com/challenges/build-a-recipe-box

截至目前,我已经能够实现将新食谱添加到列表中。

但是,我很难实施如何编辑/删除每个食谱项目列表。现在,我只想专注于如何删除每个项目。

我显示食谱列表的方式是在 RecipeBox 容器中,我在其中使用 map 函数从应用程序的状态迭代地呈现它们中的每一个,以及呈现按钮 EDIT 和 DELETE。

但我似乎无法对其附加操作。 我收到以下错误:

Uncaught TypeError: Cannot read property 'props' of undefined

RecipeBox 容器:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ListGroup, ListGroupItem, Panel, Button, Modals } from 'react-bootstrap'
import { bindActionCreators } from 'redux';
import { deleteRecipe } from '../actions/index';

class RecipeBox extends Component {
  constructor(props){
    super(props);
    this.state = {
      open: false
    };

  }
  renderRecipeList(recipeItem,index){
    const recipe = recipeItem.recipe;
    const ingredients = recipeItem.ingredients;
    return(
      <div key={index}>
        <Panel bsStyle="primary" collapsible header={<h3>{recipe}</h3>}>
          <ListGroup >
            <ListGroupItem  header="Ingredients"></ListGroupItem>
            {ingredients.map(function(ingredient,index){
              return <ListGroupItem key={index}>{ingredient}</ListGroupItem>;
            })}
            <ListGroupItem>
              <Button
                onClick={this.props.deleteRecipe(recipeItem)}
                bsStyle="danger">Delete
              </Button>
              <Button
                onClick={() => console.log('EDIT!')}
                bsStyle="info">Edit
              </Button>
            </ListGroupItem>
          </ListGroup>
        </Panel>
      </div>
    )
  }
  render(){
    return(
      <div className="container">
        <div className='panel-group'>
          {this.props.addRecipe.map(this.renderRecipeList)}
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    addRecipe : state.addRecipe
  };
}

function mapDispatchToProps(dispatch){
  return bindActionCreators({deleteRecipe}, dispatch)
}

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

这似乎很微不足道,但我一直遇到障碍..

【问题讨论】:

  • 你能把你的reducer代码给我们看看吗?

标签: javascript reactjs react-redux


【解决方案1】:

在构造函数中添加this.renderRecipeList = this.renderRecipeList.bind(this)

【讨论】:

  • 糟糕,忘记绑定了..非常感谢!
【解决方案2】:
 render(){
 return(
  <div className="container">
    <div className='panel-group'>
      {this.props.addRecipe.map(this.renderRecipeList.bind(this))}
    </div>
  </div>
 )
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多