簡體   English   中英

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

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

我正在嘗試瀏覽員工列表,當我單擊按鈕時,它會將他們的員工ID添加到數組中。 我嘗試使用.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>
)}

您正在執行:

ids: ids.push(badgeID)

這將保存不是數組的push方法的返回值,因此下次調用push時將失敗。 相反,您需要執行以下操作:

ids: [...ids, badgeID]

要么:

ids: ids.concat([badgeId])

這是因為ids.push返回新數組的長度: 檢查文檔

基本上,您將ids設置為一個整數值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM