dfilatov / vidom

Library to build UI based on virtual DOM
MIT License
415 stars 16 forks source link

Parent component this.update() does not update the children components #181

Closed JoeLanglois closed 8 years ago

JoeLanglois commented 8 years ago
class TimerContainer extends Component {
    onInit(){
        this.counter = 0

        setInterval(() => {
            this.counter = this.counter + 1
            this.update()
        }, 1000)
    }

    onRender(){
        return <Timer count={this.counter} />
    }
}

class Timer extends Component {
    onInit(props){
        this.count = props.count
    }

    onRender(){
        return <h1>{this.count}</h1>
    }
}

mountToDom(document.getElementById('app'), <TimerContainer />)

The webpage prints 0 and does not update every second. Something I am missing?

JoeLanglois commented 8 years ago

But doing...

class TimerContainer extends Component {
    onInit(){
        this.counter = 0

        setInterval(() => {
            this.counter = this.counter + 1
            this.update()
        }, 1000)
    }

    onRender(){
        return <h1>{this.counter}</h1>
    }
}
mountToDom(document.getElementById('app'), <TimerContainer />)

Works as expected.

dfilatov commented 8 years ago

Hi! You store count within Timer during initialization (onInit), but never update it. You can rewrite Timer and not store count, just use it in onRender:

class Timer extends Component {
    onRender(props){
        return <h1>{props.count}</h1>
    }
}

or if you have some reasons to store it you need to update it when new attrs is coming:

class Timer extends Component {
    onInit(props){
        this.count = props.count
    }

    onAttrsReceive(props) {
        this.count = props.count
    }

    onRender(props){
        return <h1>{this.count}</h1>
    }
}