Below is my attempt to create an array of classes. The functionality of app is next: one can add or delete extra Input box and increase or decrease its value. As a result the app displays the sum of the all present tags. The issue comes with Delete function, when deleting any of components from created list it does correct math in array but rerenders the elements incorrectly. It always deletes the last component on the list even when you try to remove any others. Any hint why it’s happening? Thanks
JavaScript
x
77
77
1
class Trade1 extends React.Component {
2
state = {
3
vl: this.props.value
4
}
5
change = (v) => {
6
let newValue
7
if (v) {
8
newValue = this.state.vl + 1
9
} else {
10
newValue = this.state.vl - 1
11
}
12
this.setState({vl: newValue})
13
this.props.onChange(newValue, this.props.index)
14
}
15
16
render() {
17
const {value, index} = this.props
18
return (
19
<div>
20
<button onClick={() => this.change(false)}>Down</button>
21
<input class="v_price" value={`${this.state.vl}`}/>
22
<button onClick={() => this.change(true)}>Up</button>
23
<button onClick={() => this.props.delete(this.props.index)}>Delete</button>
24
</div>
25
)
26
}
27
}
28
29
class Parent extends React.Component {
30
constructor(props){
31
super(props);
32
this.state = {
33
arr: [0,0,0]
34
}
35
}
36
37
onChange = (v, i) => {
38
let newArr = this.state.arr
39
newArr[i] = v
40
this.setState(newArr)
41
}
42
43
plus = () => {
44
let a = this.state.arr
45
a.push(0)
46
this.setState({arr: a})
47
}
48
49
minus = i => {
50
let a = this.state.arr
51
a.splice(i, 1)
52
console.log(a)
53
this.setState({arr: a})
54
55
}
56
57
render() {
58
return (
59
<div>
60
{this.state.arr.map((v, i) =>
61
{
62
return <Trade1 value={v} index={i} onChange={this.onChange} delete={this.minus}/>
63
}
64
)}
65
<div>{
66
this.state.arr.reduce((a, b) => a+b, 0 )
67
}</div>
68
<div><button onClick={this.plus}>Plus</button></div>
69
</div>
70
)
71
}
72
}
73
74
75
76
ReactDOM.render(<Parent />, document.getElementById('root'));
77
Advertisement
Answer
You are mutating the array, you should use filter and remove the element at index which you pass as an argument
JavaScript
1
6
1
minus = i => {
2
this.setState({
3
arr: this.state.arr.filter((x, j) => j !== i)
4
})
5
}
6