slice ตัดค่าใน array ออกตาม index

deletePerson = id => () => {
    const { people } = this.state
    const index = people.findIndex(person => person.id === id)
    const newPeople = [
      ...people.slice(0,index),
      ...people.slice(index + 1)
    ]
    this.setState({people : newPeople})
  }

Index Component Test

import { Component,Fragment } from 'react';

class Index extends Component{
  state = {
    people:[
      { id:1, name: 'Somchai',age:24},
      { id:2, name: 'Somsree',age:25},
      { id:3, name: 'Somset',age:26}
    ],
    text: ''
  }


  deletePerson = id => () => {
    const { people } = this.state
    const index = people.findIndex(person => person.id === id)
    const newPeople = [
      ...people.slice(0,index),
      ...people.slice(index + 1)
    ]
    this.setState({people : newPeople})
  }

  addPerson = () => {
    const { text, people } = this.state
    const person = {id: +new Date(), name: text}
    this.setState({ people: [...people,person], text: '' })
  }

  changeText = (event) => {
    this.setState({ text: event.target.value})
  }

  render(){
    const { text, people} = this.state
    return (
      <Fragment>
        <input type="text" onChange={this.changeText} value={text}/>
        <button onClick={this.addPerson}>Add</button>
        <ul>
          {people.map(person => <li key={person.id}>{person.name}<button onClick={this.deletePerson(person.id)} >Delete</button></li>)}
        </ul>
      </Fragment>
    )
  }
}

export default Index;

ผลลัพธ์โปรแกรม หลังจากกดปุ่ม Delete มันจะลบได้อย่างถูกต้อง โดยใช้หลัก function programming คือการที่ไม่ไปแก้ไข object เก่า แต่ใช้ method สำหรับสร้าง object ใหม่ เช่นในที่นี้คือ slice

Related posts:

This entry was posted in functional_programming. Bookmark the permalink.