【问题标题】:Delete item from array in Redux从 Redux 中的数组中删除项目
【发布时间】:2020-04-07 16:26:49
【问题描述】:

我是 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
      };

但是,如果我删除第一个,那么它会删除第一个和最后一个!!!

我不知道发生了什么,如果有人能提出正确的解决方案,我将不胜感激。谢谢

【问题讨论】:

  • id是代表serviceList中元素的索引还是?
  • 是的,'id'代表'serviceList'中item的索引

标签: arrays react-redux


【解决方案1】:

如果id 表示servicesList 中元素的索引,则可以使用数组的filter 方法删除某些元素。

您的删除方法将如下所示:

case DELETE_SERVICE:
  delete serviceList[action.id]

  return {
    ...state,   
    serviceList: serviceList.filter((e, index) => index !== action.id)
  };

此代码将从action 对象中过滤索引等于id 的元素。

【讨论】:

  • 是的,我也尝试过这样使用过滤器。如果我在减速器文件中打印出“serviceList”,那么我可以看到它工作正常,但由于某种原因,当我在“Service.js”中调用函数“deleteService”时,列表没有相应更新
  • “列表没有相应更新”是什么意思?更新后列表的新状态是什么?
  • 在'service.js'中,我连接到Store并对'this.props.serviceList'执行删除操作。出于某种原因,商店中发生的一切都没有在“this.props.serviceList”中更新。例如,删除第二个条目后,reducer 中“serviceList”的大小为 1,而“this.props.serviceList.length”为 2,这意味着没有任何内容被删除。这里一定是出了什么问题,我无法弄清楚。
【解决方案2】:

谢谢大家。我发现我的动画列表视图存在问题,而不是 reducer 本身的问题。该问题现已关闭。

【讨论】:

    猜你喜欢
    • 2019-02-15
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    • 2021-10-03
    • 2021-10-19
    • 2014-09-21
    相关资源
    最近更新 更多