【问题标题】:Remove item from array in redux从redux中的数组中删除项目
【发布时间】:2019-02-15 18:36:09
【问题描述】:

我正在尝试使用 redux 从数组中添加/删除项目,这些项目将添加到数组中,但是当我尝试删除一个项目时,它看起来像是在改变数组并添加项目而不是删除

尝试添加/删除项目后,我的状态看起来与此类似

[item1, item2, [item1, item2]]

如何从我的数组中删除项目?

状态

state.filtered.cities: []

Filter.js

import React from 'react'
import styled from 'styled-components'
import { connect } from 'react-redux'
import * as actions from './actions'

class Filter extends React.Component {

  handlecity = (city) => {
    this.props.addCity(city)
  }

  handleRemoveCity = (city) => {
    this.props.removeCity(city)
  }



  render() {

    const options = [
   'item1','item2'
    ]

    return(
      <Wrap>
        {options.map((option,index) =>
          <Cell>
            <OptionWrap key={index} onClick={()=> this.handlecity(option)}>
              {option}
            </OptionWrap>
            <OptionWrap key={index} onClick={()=> this.handleRemoveCity(option)}>
              remove {option}
            </OptionWrap>
            {console.log(this.props.city && this.props.city)}
          </Cell>
        )}
      </Wrap>
    )
  }
}

const mapStateToProps = state => ({
  city: state.filtered.cities
})

const mapDispatchToProps = {
  ...actions,
}

export default connect(mapStateToProps, mapDispatchToProps)(Filter);

actions.js

import {
  ADD_CITY, REMOVE_CITY
} from '../../Constants'

export function addCity(city) {
  return {
    type: 'ADD_CITY',
    city
  }
}

export function removeCity(city) {
  return {
    type: 'REMOVE_CITY',
    city
  }
}

reducer.js

import {
  ADD_CITY, REMOVE_CITY
} from '../Constants';

const cityReducer = (state = [], action) => {
  switch (action.type) {
    case ADD_CITY:
      return [
        ...state,
        action.city
      ]
    case REMOVE_CITY:
      return [
        ...state,
        state.filter(city => city !== action.city),
      ]
    default:
      return state;
  }
}

export default cityReducer;

【问题讨论】:

标签: javascript reactjs redux react-redux


【解决方案1】:

为什么不简单:

reducer.js

import {
  ADD_CITY, REMOVE_CITY
} from '../Constants';

const cityReducer = (state = [], action) => {
  switch (action.type) {
    case ADD_CITY:
      return [
        ...state,
        action.city
      ]
    case REMOVE_CITY:
      return state.filter(city => city !== action.city)
    default:
      return state;
  }
}

export default cityReducer;

【讨论】:

    【解决方案2】:

    你的 remove city reducer 应该是这样的

    case REMOVE_CITY:
      return [
        ...state.filter(city => city !== action.city),
      ]
    

    否则,您将添加 所有以前的项目以及过滤后的列表。

    【讨论】:

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