我是Redux的新手,正在寻找一种从Redux中现有数组中删除JSON对象的方法。我已经尝试了几种方法,但是都没有用。减速器的代码如下:
const initialState = {serviceList: [{name: 'Ancestome', connectedAt: '08/03/2020'},{name: '23AndMe', connectedAt: '09/03/2020'},{name: 'Cancer Research UK', connectedAt: '09/03/2020'}]}
const serviceReducer = (state = initialState, action) => {
let serviceList = [...state.serviceList]
switch (action.type) {
case DELETE_SERVICE:
delete serviceList[action.id]
return {
...state,
serviceList: serviceList
};
default:
return state
}
}
export default serviceReducer
File service.js
class Services extends React.Component {
constructor(props) {
super(props);
this.addNewEle = false;
this.state = {disabled: false};
}
afterAnimationComplete = () => {
this.setState({ disabled: false });
}
deleteFromService = (id) => {
this.props.deleteService(id);
this.addNewEle = false;
this.setState({disabled: false});
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
}
render() {
return (
<View style={styles.container} >
<Header
placement="left"
centerComponent={{ text: 'Service', style: { color: '#fff', fontSize: 24 } }}
/>
<ScrollView
ref={scrollView => this.scrollView = scrollView}
onContentSizeChange={() => {
this.addNewEle && this.scrollView.scrollToEnd();
}}
>
<View style={{ flex: 1, padding: 4 }}>
{Object.keys(this.props.serviceList).map((id) => {
return (
<ServiceItem
key={id}
id={id}
item={this.props.serviceList[id]}
removeItem={(id) => this.deleteFromService(id)}
afterAnimationComplete={this.afterAnimationComplete}
/>
)
})}
</View>
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create(
{
container: {
flex: 1,
},
title: {
backgroundColor: 'transparent',
color: 'black',
fontSize: 24,
paddingLeft: 10,
paddingTop: 50,
}
});
const mapStateToProps = (state) => ({ serviceList: state.serviceReducer.serviceList });
const mapDispatchToProps = (dispatch) => ({
deleteService: (serviceItem) => {
dispatch(deleteService(serviceItem));
},
});
export default connect(mapStateToProps, mapDispatchToProps)(Services);
在上面的代码中,如果我从阵列中删除一个条目但第二次尝试失败,则可以使用。例如,我删除第一个(id = 0),然后保留两个条目(id = {1,2})。现在,例如,如果我继续删除第二个条目(id = 1),它没有删除此条目,奇怪的是它返回了两个条目(id = {0,2})!当我尝试删除最后一个条目时,发生了类似的事情。
我也尝试了以下代码:
let newList = serviceList.slice(0, action.id).concat(serviceList.slice(action.id + 1));
return {
...state,
serviceList: newList
};
但是,如果我删除第一个,则它将删除第一个和最后一个!!!
我不知道发生了什么,如果有人可以提出正确的解决方案,我将不胜感激。谢谢
答案 0 :(得分:1)
如果id
表示servicesList
中元素的索引,则可以使用数组的filter
方法删除某些元素。
您的删除方法将如下所示:
case DELETE_SERVICE:
delete serviceList[action.id]
return {
...state,
serviceList: serviceList.filter((e, index) => index !== action.id)
};
此代码将过滤元素与索引id
中的action
相等的元素。
答案 1 :(得分:0)
谢谢大家。我发现动画列表视图有问题,而不是reduce本身有问题。该问题现已关闭。