【发布时间】: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