简体   繁体   English

在onClick方法上,我不能两次使用.push

[英]On an onClick method, I can't use a .push twice

I'm trying to go through a list of employees and when I click a button it adds their employee ID in an array. 我正在尝试浏览员工列表,当我单击按钮时,它会将他们的员工ID添加到数组中。 I try to do this with a .push method onto the array, but it only works once, and then when I try to push the button for the next employee it says .push is not a function. 我尝试使用.push方法在数组上执行此操作,但是它只能运行一次,然后当我尝试按下下一位员工的按钮时,它说.push不是函数。

constructor(props:any){
    super(props);
    this.state={
        employees:[{name: 'joe', id: 12345},{name: 'kelly', id: 12321},{name: 'Jessica', id: 12255},{name: 'Paul', id: 98798}],
        ids:[],
        badgeID: '',
        currentEmployee: null
    }
}


check = () => {
    const {ids, badgeID, employees} = this.state

    let filteredEmployee = employees.filter(employee => {
        return employee.id === Number(badgeID)
    })

    this.setState({
        currentEmployee: filteredEmployee,
        drinkModal: true,
        ids: ids.push(badgeID)
    })
    console.log('ids', this.state.ids)
}


handleChange = (e: any, type: string) => {
    if(type === 'badge'){
        this.setState({badgeID: e.target.value})
    }
}

render(){
    return(
        <TextField onChange={e => this.handleChange(e, 'badge')}/>
        <Button onClick={this.check}>Add Employee</Button>
)}

You are doing: 您正在执行:

ids: ids.push(badgeID)

This saves the return value of the push method which is not an array, so the next time you call push it fails. 这将保存不是数组的push方法的返回值,因此下次调用push时将失败。 Instead you need to do something like: 相反,您需要执行以下操作:

ids: [...ids, badgeID]

or: 要么:

ids: ids.concat([badgeId])

This is because ids.push returns the length of the new array: check the docs 这是因为ids.push返回新数组的长度: 检查文档

Basically you are setting to ids an integer value. 基本上,您将ids设置为一个整数值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM