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

北慕城南 提交于 2019-12-24 01:15:00

问题


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");
    //...
}}

回答1:


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(); });



回答2:


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




回答3:


In your component, whenever you directly manipulate state you need to use the following:

this.setState({});

Complete code:

class TODOItems extends React.Component {

constructor() {
    super();

    this.loadItems();
}

loadItems() {
  let newState = Store.getItems();
    this.setState = {

        todos: newState
    };
}

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");
    //...
}}


来源:https://stackoverflow.com/questions/36185577/why-react-doesnt-call-render-when-state-is-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!