Redux中如何从数组中删除一个条目

3
我正在尝试使用redux向数组中添加/删除项目,当我尝试删除一个项目时,它似乎会改变数组并添加项目,而不是删除。在尝试添加/删除项目后,我的状态看起来与以下类似:[item1, item2, [item1, item2]]。如何从数组中删除项目? state 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;

可能是使用redux删除项目的正确方法吗?的重复问题。 - streletss
这个问题和那里的答案类似,但我遇到了一些困难,无法解决。 - tom harrison
2个回答

12

为什么不简单地:

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

你的移除城市reducer应该如下所示:

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

否则,您将添加所有先前的项和筛选列表。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接