react-native - 在反应本机redux中将对象连接到数组中
问题描述
我在使用 redux 将对象连接到数组时遇到问题。当用户单击按钮时,我想将对象连接到数组中,但总是显示一个错误,称为无法读取 null 的属性“concat”。这是我的代码:
addToCartHandler= ()=>{
const {phoneNumber,accessToken,ctr} = this.props;
let {dataSource} = this.state;
const cart = {title:dataSource.title,image:dataSource.image,id:dataSource.id,count:ctr,price:(dataSource.price-dataSource.discount)*ctr};
this.props.onCart(cart);}
.
.
.
.
const mapDispatchToProps = dispatch => {
return {
onLogin: () => dispatch({ type: actionTypes.SAVEPHONE }),
onToken: token => dispatch({ type: actionTypes.SAVEACCESSTOKEN, token }),
onCart:(cart)=>dispatch({type:actionTypes.CARTPRODUCT,cart})
}
}
这是我的减速机:
const initialState = {
cartProduct:[],
}
const ShopReducer = (state=initialState,action)=>{
switch(action.type){
case actionTypes.CARTPRODUCT:
return {
...state,
cartProduct:state.cartProduct.concat(action.cart)
}
default:
return state
}
}
解决方案
您不能将数组与对象连接起来。而是用数组包装您的对象,如代码段所示
const initialState = {
cartProduct:[],
}
const ShopReducer = (state=initialState,action)=>{
switch(action.type){
case actionTypes.CARTPRODUCT:
return {
...state,
cartProduct:state.cartProduct.concat([action.cart]) // change here
}
default:
return state
}
}
没测试!!希望能帮助到你 :)
推荐阅读
- r - 将字符串转换为数字时出错
- html - Powershell 服务状态 || HTML 输出
- xcode - 为什么 Xcode 10 会崩溃?
- android - 在 NDK for Android 上编译 stressapptest
- vba - VBA - 将数据从一个工作簿推送到另一个工作簿,而不考虑文件名
- githooks - gitolite 设置解决了什么问题?
- c# - 计算组中列的变化并根据标准进行提取
- ios - 无法从 Windows 10 Visual Studio 安装 Xamarin.iOS 11.14
- arrays - 无法使用可选的通用数组推断通用参数 T
- entity-framework - 查询数据库和未保存的更改以使用 Entity Framework 6 进行验证