从数组中删除项目(如果存在)React

时间:2017-07-21 09:48:36

标签: javascript arrays reactjs

我正在使用react immutability helper来推送/删除我的数组中的项目,我遇到的问题是它会在Clicked时添加一个项目,但再次点击它会继续添加项目。

我试图检查handleAdd函数中是否存在该项,如果它不重新添加,但此函数不起作用,无论如何都会添加该项。

如果项目已存在,如何阻止添加到数组?如果它们确实存在,请将它们从数组中删除?

https://www.webpackbin.com/bins/-KpZSs5nSCr8YQ9_xPFI

Hello.js

import React, { Component } from 'react';
import update from 'immutability-helper'
import styled from 'styled-components'
import FilterList from './FilterList'

const Wrapper = styled.div`
  max-width:1280px;
  background: papayawhip;
  margin: 0 auto;
  padding:20px;
`

const Grid = styled.div`
  display:flex;
  flex-wrap:wrap;
`

const Cell = styled.div`
  flex: 0 0 25%;
  padding: 20px;
`

export default class Hello extends Component {
  constructor(props) {
    super(props)
    this.state = {
      items: [
        {id: 1, cat: 'fruit', text: 'apples'},
        {id: 2, cat: 'fruit', text: 'oranges'},
        {id: 3, cat: 'fruit', text: 'peaches'},
        {id: 4, cat: 'veg', text: 'carrots'},
        {id: 5, cat: 'veg', text: 'aubergine'},
        {id: 6, cat: 'veg', text: 'peaches'},
        {id: 7, cat: 'bread', text: 'olive bread'},
        {id: 8, cat: 'bread', text: 'bread roll'},
        {id: 9, cat: 'bread', text: 'bagel'}
      ],
      filterItems: [
        {id: 1, text: 'bread'},
        {id: 2, text: 'fruit'},
        {id: 3, text: 'vegetables'}
      ],
      filter: [
        {text: 'bread'}
      ]
    }
    this.handleFilterChange = this.handleFilterChange.bind(this)
  }

  handleFilterChange(filter) {
    this.setState({filter: filter})
  }

  render() {
    return (
      <Wrapper>
        <div>
        <FilterList
          value={this.state.filter}
          onChange={this.handleFilterChange}
          filterItems={this.state.filterItems}
        />
        </div>
        <Grid>
          {
            this.state.items.filter(items => this.state.filterItems.map(item => item.text)
            .indexOf(items.cat) !== -1 )
            .map(item =>
                <Cell>
                    {console.log(this.state.filter.text)}
                    <div>{item.cat}</div>
                    <div>{item.text}</div>
                </Cell>
            )
          }
        </Grid>
      </Wrapper>
    )
  }
}

//  <pre>{JSON.stringify(this.state, null, 4)} </pre>

FilterList.js

import React, { Component } from 'react';
import update from 'immutability-helper'
import styled from 'styled-components'

const FilterListBg = styled.div`
  background: lightblue;
  width: 100%;
  height: 60px;
`

const FilterListItem = styled.div`
  float: left;
  height: 40px;
  width: 100px;
  padding:10px;
  border-right: 1px solid #ff00ff;
`

const FilterBg = styled.div`
  width: 100%;
  height:40px;
  background: #fff;
  margin-top:20px;
`

const FilterItem = styled.div`
  float: left;
  height: 40px;
  width: 100px;
  padding:10px;
  border-right: 1px solid #ff00ff;
`

export default class FilterList extends Component {
  constructor() {
    super()

    this.state = {
      search: ''
    }
    this.handleAdd = this.handleAdd.bind(this)
    this.handleRemove = this.handleRemove.bind(this)
    this.handleFilterUpdate = this.handleFilterUpdate.bind(this)
  }

   handleAdd(item) {
    if (this.props.value.includes(item)) {
    console.log('this exists')
    }
    else{
     const value = update(this.props.value, {
      $push: [
        {
          text: item,
          id: Math.random()
        }
      ]
    })
    this.props.onChange(value)
    }
  }

  handleRemove(index) {
      const value = update(this.props.value, {
        $splice: [
          [index, 1]
        ]
      })
      this.props.onChange(value)
    }

  handleFilterUpdate(update) {
    this.setState({ search: event.target.value })
  }

  render() {
    return (
      <div>
        <input
          type="text"
          value={this.state.search}
          onChange={this.handleFilterUpdate}
          placeholder="Hledat podle nazvu"
        />
        {this.state.search}
        <FilterListBg>
          {
            this.props.filterItems.filter(items => items.text.toLowerCase().indexOf(this.state.search.toLowerCase()) >= 0)
            .map((item,cat,index) =>
              <FilterListItem key={item.id} onClick={()=>this.handleAdd(item.text)}>
                {item.text}
              </FilterListItem>
            )
          }
        </FilterListBg>
        Aktivní filtry
        <FilterBg>
          {
            this.props.value.map((item, index) =>
            <FilterItem key={item.id} onClick={this.handleRemove}>
              {item.text}
            </FilterItem>
            )
          }
        </FilterBg>

      </div>
    )
  }
}

1 个答案:

答案 0 :(得分:0)

你可以使用拼接功能

来做到这一点
deleteItem : function(index){
            if(indexexists)
{
            var newtodo = this.state.Todo;//considering todo as root element
            var allItems = this.state.Todo[index].items.slice(); //copy array
            allItems.splice(index, 1); //remove element
            newtodo[index].items = allItems;
            this.setState({
                Todo: newtodo
            });
        },

}

}