如何解决Redux无法将道具添加到状态
我想将道具basket: "true"
添加到产品中,然后按一下。但这是行不通的。
动作:
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的完整代码(不包含导入和样式):
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);
篮子。在这里,我想用篮子展示我的产品:“ true”。我在名为showProductsList()的函数中执行此操作,并在View中显示它:
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);
但是它什么也没显示。我该怎么办?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。