Answer the question
In order to leave comments, you need to log in
Redux does not add a property to state. What to do?
I want to add a basket: "true" property to every product that I click on.
Action.js:
export const addToBasket = (name) => {
return {
type: "BASKET",
payload: name,
};
}
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;
};
}
<Text onPress={() => this.props.addToBasket.bind(this, this.props.product.name)} style={styles.name}>{this.props.product.name}</Text>:
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);
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);
Answer the question
In order to leave comments, you need to log in
case 'BASKET':
return {
...state,
products: state.products.map(n => n.name === action.payload
? { ...n, basket: true }
: n
),
};
onPress={() => this.props.addToBasket.bind(this, this.props.product.name)}
onPress={() => this.props.addToBasket(this.props.product.name)}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question