【问题标题】:Splice removing the wrong index拼接删除错误的索引
【发布时间】:2021-06-14 20:09:39
【问题描述】:

所以我正在尝试构建一个动态文本字段,一切正常,但我在从状态/数组中删除数据时遇到问题。 splice 总是删除最后一个索引而不是自定义索引。这是我的整个代码。顺便说一句,我正在使用 reactjs 作为前端框架。

import React from 'react'

class Form extends React.Component {
    constructor(props){
        super(props)

        this.state = {
            firstName: "",
            lastName: "",
            books: []
        }

        this.onSubmitHandle = this.onSubmitHandle.bind(this)
        this.onChangeHandle = this.onChangeHandle.bind(this)
    }

    onSubmitHandle = (event) => {
        event.preventDefault()
        console.log(this.state)
    }

    onChangeHandle = (event) => {
        event.preventDefault()

        if(["book"].includes(event.target.name)) {
            let books = [...this.state.books]
            books[event.target.dataset.id][event.target.name] = event.target.value
        } else {
            this.setState({
                [event.target.name]: event.target.value
            })
        }
    }

    addNewRow = () => {
        this.setState((prevState) => ({
            books: [...prevState.books, { "book": "" }]
        }))
    }

    removeRow = (index) => {
    const newBooks = [...this.state.books];
    newBooks.splice(index, 1)
    this.setState({books: newBooks})
    }
     
    
    render() {
        return(
            <div>
                <form onSubmit={this.onSubmitHandle}>
                    <input type="text" name="firstName" onChange={this.onChangeHandle} placeholder="First Name" />
                    <input type="text" name="lastName" onChange={this.onChangeHandle} placeholder="Last Name" />
                    <br></br>
                    {
                        this.state.books.map((val, i) => {
                            return(
                                <div key={i}>
                                    <input type="text" data-id={i} onChange={this.onChangeHandle} name="book" placeholder={i} />
                                    <button type="button" onClick={this.removeRow.bind(this, i)}>Remove {i}</button>
                                </div>
                            )
                        })
                    }
                    <br></br>
                    <button type="button" onClick={this.addNewRow.bind(this)}>Add</button>
                    <br></br>
                    <button type="submit">Submit</button>
                </form>
            </div>
        )
    }
}

export default Form

【问题讨论】:

    标签: javascript arrays reactjs splice array-splice


    【解决方案1】:

    函数本身和拼接工作正常。您的问题与反应状态更新有关。

    您的代码有几个问题。

    首先,您仅以一种方式绑定输入元素,因此如果有状态更新,它不会是反应性的。此外,由于它的值没有绑定到变量,因此如果元素的数量发生变化,react 不会发现保持它处于活动状态的任何问题。您可以在此处阅读有关密钥的更多信息:https://reactjs.org/docs/lists-and-keys.html

    解决问题。将value={val.book} 设置为输入元素。

    如果您执行步骤 1 中建议的更改,您会发现您的代码存在另一个问题,即您的 onChangeHandle 函数中有错误。基本上,您不会在此处更新状态,因为您只是更新对象的值。一般来说,我认为在使用 react 时避免此类分配是可取的。尽可能尝试使用纯函数。无论如何,尝试将您的更改处理程序更改为以下内容:

    onChangeHandle = (event) => {
      event.preventDefault()
      
      if(event.target.name === 'book') {
        let books = [...this.state.books]
        books[event.target.dataset.id][event.target.name] = event.target.value
        this.setState({
            books,
        })
        return;
      }
    
      this.setState({
          [event.target.name]: event.target.value
      });
    

    这将确保每当您更改输入值时状态都会更新,并且该值会正确反映在您的输入元素中。

    【讨论】:

    • 我建议你再看一下 react 基础知识,尤其是关于状态管理和所有相关概念的:)
    猜你喜欢
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多