I'm creating a packing list for a holiday.
I have these 2 cases:
switch(action.type) {
case 'ADD_ITEM': {
const items = [].concat(state.items).concat(action.data)
return { items }
}
case 'ITEM_ALREADY_ADDED': {
state.items.map((item) => (
item.name === action.data.name ? alert('Item already added') : item
))
return { ...state }
}
}
When I type into the input another item
and then click add, it calls the second case statement (item already exists). tTis is working, however, I broke the add item case.
So I'm trying to do a ternary and I'm not sure what to put on the right-hand side of the :
if the item isn't there. This is where I want to do my check and then call the other action.
So two questions:
答案 0 :(得分:0)
第一个问题
你可以这样做
switch(action.type){
case 'ADD_ITEM': {
const items = [].concat(state.items).concat(action.data)
return { ...state, items }
}
// dont do the alert here, instead access the items array in your component using connect and mapStateToProps. do looing there and check whether it is already existing or not. depending on which dispatch action. you dont need to have ITEM_ALREADY_ADDED case.
}
//您的组件和第二个问题
class A extends React.Component {
add = () => {
const {items} = this.props
// write yout logic here and check whether the item is already availle
//and accordingly dispatch the action
}
render() {
return (
<div>
<button onClick={this.add}>Add</button>
</div>
)
}
}
function mapStateToProps(state) {
items : state.yourreducrename.items,
}
注意:这只是更高级别的概述,请调整代码 相应