【问题标题】:React es6, Remove item from array, by changing propsReact es6,通过更改道具从数组中删除项目
【发布时间】:2016-02-20 11:40:03
【问题描述】:

我是 React 的新手,现在我正在做一个项目,用户应该能够选择基本成分,并将其添加到数组中。通过单击另一种基本成分,应从阵列中删除第一个基本成分。现在选择的成分只有在点击同一个成分时才会被移除。

我希望在单击另一个时将其删除。请帮忙:)

import React from 'react';
import Actions from '../../../actions/actions';
import BaseIngredientButton from './BaseIngredientButton';

class BaseIngredientItem extends React.Component {
    _OnClick (props) {

        if (this.props.isChosen) {
            Actions.removeItem(this.props.baseIngredient);
        } else {
            Actions.addItem(this.props.baseIngredient)
            Actions.setBaseIngredient( this.props.baseIngredient );
        }

        console.log(this.props.isChosen)

    }

    render () {
       return (
           <BaseIngredientButton isChosen={this.props.isChosen} onClick={ this._OnClick.bind(this)} txt={ this.props.baseIngredient.name } />
       )
    }
}

BaseIngredientItem.propTypes = { 
    baseIngredient: React.PropTypes.object.isRequired,
    isChosen: React.PropTypes.bool
}

export default BaseIngredientItem;

这是我的 store.js

let _cart = [];

const _removeItem = ( item ) => {
  _cart.splice( _cart.findIndex( i => i === item ), 1 );
  console.log("Ingredients in cart after removal", _cart);
};

const _getItemInCart = ( item ) => {
  return _cart.find( ingredient => ingredient.name === item.name )
};

const _addItem = ( item ) => {
  if (!_getItemInCart( item )) {
    _cart.push(item);
  } 
  console.log("Ingredients in cart after addition", _cart);
};

let _currentBaseIngredient = {};

const _setCurrentBaseIngredient = ( baseIngredient ) => {
  _currentBaseIngredient = baseIngredient
};

这是我的 action.js

 addItem( item ){
    dispatch({
       actionType: AppConstants.ADD_ITEM, 
       item
     })
  },
  removeItem( item ){
    dispatch({
      actionType: AppConstants.REMOVE_ITEM, 
      item
    })
  },
  setBaseIngredient( baseIngredient ){
    dispatch({
      actionType: AppConstants.SET_BASE_INGREDIENT, 
      baseIngredient
    })
  },

【问题讨论】:

  • 假设您使用的是 Flux 模式,这似乎可以在 Store 中进行管理。你能展示你的Actions 对象和它与之通信的商店吗?
  • 当然。我在原始帖子中添加了它:)

标签: reactjs ecmascript-6


【解决方案1】:

您的 BaseIngredientItem 组件不知道数组中是否还有其他基本成分,所以正如我在评论中提到的,这肯定是在 Store 级别检查的内容。

有什么方法可以确定一个项目是否属于基础类型?如果有,您可以在 addItem 函数中检查它是否存在:

(请不要介意一些伪代码)

const _addItem = ( item ) => {
  if (item is a base ingredient)
    removeCurrentBaseIngredient()

  if (!_getItemInCart( item )) {
      _cart.push(item);
  } 
  console.log("Ingredients in cart after addition", _cart);
};

const removeCurrentBaseIngredient = () => {
  _removeItem( _currentBaseIngredient );
};

由于商店已经知道_currentBaseIngredient,您应该可以很容易地查找它并调用_removeItem 将其从_cart 中删除。

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 2021-11-11
    相关资源
    最近更新 更多