【问题标题】:Adding and deleting array of classes error添加和删​​除类数组错误
【发布时间】:2020-08-14 07:46:37
【问题描述】:

下面是我尝试创建一个类数组。应用程序的功能是:可以添加或删除额外的输入框并增加或减少其值。结果,应用程序显示所有当前标签的总和。问题来自 Delete 函数,当从创建的列表中删除任何组件时,它会在数组中进行正确的数学运算,但会错误地重新渲染元素。即使您尝试删除任何其他组件,它也会始终删除列表中的最后一个组件。任何提示为什么会发生?谢谢

class Trade1 extends React.Component {
  state = {
    vl: this.props.value
  }
  change = (v) => {
    let newValue
    if (v) {
      newValue = this.state.vl + 1
    } else {
      newValue = this.state.vl - 1
    }
    this.setState({vl: newValue})
    this.props.onChange(newValue, this.props.index)
  }

  render() {
    const {value, index} = this.props
    return (
      <div>
      <button onClick={() => this.change(false)}>Down</button>
      <input class="v_price" value={`${this.state.vl}`}/>
      <button onClick={() => this.change(true)}>Up</button>
      <button onClick={() => this.props.delete(this.props.index)}>Delete</button>
      </div>
    )
  }
}

class Parent  extends React.Component {
  constructor(props){
  super(props);
  this.state = {
    arr: [0,0,0]
  }
 }

  onChange = (v, i) => {
    let newArr = this.state.arr
    newArr[i] = v
    this.setState(newArr)
  }

  plus = () => {
    let a = this.state.arr
    a.push(0)
    this.setState({arr: a})
  }

  minus = i => {
    let a = this.state.arr
    a.splice(i, 1)
    console.log(a)
    this.setState({arr: a})

  }

  render() {
    return (
      <div>
      {this.state.arr.map((v, i) =>
        {
            return <Trade1 value={v} index={i} onChange={this.onChange} delete={this.minus}/>
        }
      )}
      <div>{
        this.state.arr.reduce((a, b) => a+b, 0 )
      }</div>
      <div><button onClick={this.plus}>Plus</button></div>
      </div>
    )
  }
}



ReactDOM.render(<Parent />, document.getElementById('root'));

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您正在改变数组,您应该使用过滤器并删除您作为参数传递的索引处的元素

      minus = i => {
        this.setState({
          arr: this.state.arr.filter((x, j) => j !== i)
        })
      }
    

    【讨论】:

      【解决方案2】:

      问题

      你有一些状态突变。尝试使用功能状态更新并总是返回新的状态对象。

      onChange = (v, i) => {
        this.setState(prevState => ({
          arr: prevState.arr.map((el, index) => index === i ? v : el)
        }));
      }
      
      plus = () => {
        this.setState(prevState => ({
          arr: [...prevState.arr, 0],
        }));
      }
      
      minus = i => {
        this.setState(prevState => ({
          arr: prevState.arr.filter((_, index) => index !== i),
        }));
      }
      

      【讨论】:

        猜你喜欢
        • 2019-04-09
        • 1970-01-01
        • 2011-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多