I have an array, I have 2 components(child and parent). I iterate through array within parent component, I render child components, I give them props with data from array.
Child components have their props translated to state and then have increment and decrement that state.
Parent component can add new item into array and re-render. BUT. If i unshift() new item in front of the array, i get last item from array added to the screen instead of new one to the front.
QUESTION: Why it renders good with .push() and bad with .unshift(). Also everything is ok with concat and [newItem, ...oldArray], but bad with same things when i add items in front of the array? Also how to properly .unshift() new items(comments, counters, images, posts, eg anything) into state, so they render first?
PS: Anything i do (concat, slice, ...array, unshift, react's immutability helper) doesn't seem to work properly. Mobx and Redux didn't help.
PS: This also occurs with Mithril, Inferno and Aurelia.
import React from 'react'
import {render} from 'react-dom'
var Component = React.Component
var data = [0, 12, -10, 1, 0, 1]
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
counter: data
}
this.addCounter = this.addCounter.bind(this)
}
addCounter(e){
let newArr = [1, ...this.state.counter]
this.setState({
counter: newArr
})
}
render() {
if(this.state.counter){
return (
<div>
<button onClick={this.addCounter}>add counter</button>
{this.state.counter.map(e=>{
return(
<Counter count={e}/>
)
})}
</div>
)
} else {
return(
<div>loading...</div>
)
}
}
}
class Counter extends Component {
constructor(props) {
super(props)
this.state = {
count: this.props.count
}
this.increment = this.increment.bind(this)
this.decrement = this.decrement.bind(this)
}
increment(e){
this.setState({count: this.state.count + 1})
}
decrement(e){
this.setState({count: this.state.count - 1})
}
render() {
return (
<span>
<b onClick={this.increment}>+</b>
<i>{this.state.count}</i>
<b onClick={this.decrement}>-</b>
</span>
)
}
}
render(<App/>, document.getElementById('root'))