Я хочу добавлять свойство basket: "true" к каждому продукту, на название которого я кликнул.
Action.js:
export const addToBasket = (name) => {
return {
type: "BASKET",
payload: name,
};
}
Reducer:
import Alert from 'react-native'
export default function (state=null, action) {
switch (action.type) {
case "BASKET":
var productToUpdate = state.products.find(item => item.name === action.payload);
productToUpdate = { ...productToUpdate, basket: true }
var products = state.products.filter(item => item.name !== productToUpdate.name);
Alert.alert(productToUpdate)
return { ...state, ...state.products, productToUpdate }
break;
default:
return state;
};
}
ProductDetails. Здесь я использую редюсер в
<Text onPress={() => this.props.addToBasket.bind(this, this.props.product.name)} style={styles.name}>{this.props.product.name}</Text>:
Вот полный код ProductDetails'a(за исключением стилей и импортов):
ProductDetails extends Component {
render() {
const { navigation } = this.props;
if (!this.props.product) {
return (
<View>
<Text>Choose a product</Text>
</View>
);
}
return (
<View style={styles.productDetailsContainer}>
<Image
style={styles.productImg}
source={{
uri: this.props.product.img,
}}
/>
<View styles={styles.row}>
<View>
<Text onPress={() => this.props.addToBasket.bind(this, this.props.product.name)} style={styles.name}>{this.props.product.name}</Text>
<Text style={styles.price}>{this.props.product.price}</Text>
</View>
<Text style={styles.flexEnd} onPress={() => navigation.navigate('Basket')}>Привет!</Text>
</View>
</View>
);
}
}
function mapStateToProps (state) {
return {
product: state.active
};
}
function matchDispatchToProps (dispatch) {
return bindActionCreators({addToBasket: addToBasket}, dispatch)
}
export default connect (mapStateToProps, matchDispatchToProps)(ProductDetails);
Basket. Здесь я вывожу продукты с basket: "true" при помощи функции showProductsList()
class Basket extends Component {
render() {
const showProductsList = (type, maxlength) => {
var currentLength = 0;
return this.props.products.map ((product) => {
if(product.basket == type & currentLength < maxlength) {
currentLength += 1;
return (
<View key={product.id}>
<Image
source={{
uri: product.img,
}}
/>
<View>
<Text>{product.name}</Text>
<Text>Price: {product.price}</Text>
</View>
</View>
);
}
})
}
if (!this.props.products) {
return (
<View>
<Text>Выберите товар</Text>
</View>
);
} else {
return (
<View>
{showProductsList("true", 4)}
</View>
)
}
}
}
function mapStateToProps(state) {
return {
products: state.products
};
}
export default connect(mapStateToProps)(Basket);