Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why react doesn't call render when state is changed?

I have problem with automatically re-rendering view, when state is changed. State has been changed, but render() is not called. But when I call this.forceUpdate(), everything is ok, but I think that's not the best solution. Can someone help me with that ?

class TODOItems extends React.Component {

constructor() {
    super();

    this.loadItems();
}

loadItems() {
    this.state = {
        todos: Store.getItems()
    };
}

componentDidMount(){
    //this loads new items to this.state.todos, but render() is not called
    Store.addChangeListener(() => { this.loadItems(); this.forceUpdate(); });
}

componentWillUnmount(){
    Store.removeChangeListener(() => { this.loadItems(); });
}

render() {

    console.log("data changed, re-render");
    //...
}}
like image 911
Jozef Cipa Avatar asked Mar 15 '26 08:03

Jozef Cipa


2 Answers

You should be using this.state = {}; (like in your loadItems() method) from the constructor when you are declaring the initial state. When you want to update the items, use this.setState({}). For example:

constructor() {
    super();

    this.state = {
        todos: Store.getItems()
    };
}

reloadItems() {
    this.setState({
        todos: Store.getItems()
    });
}

and update your componentDidMount:

Store.addChangeListener(() => { this.reloadItems(); });
like image 188
Joseph Roque Avatar answered Mar 17 '26 21:03

Joseph Roque


You sholdn't mutate this.state directly. You should use this.setState method.

Change loadItems:

loadItems() {
    this.setState({
        todos: Store.getItems()
    });
}

More in react docs

like image 32
Aleksandr Petrov Avatar answered Mar 17 '26 20:03

Aleksandr Petrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!