为什么状态改变时反应不调用渲染?

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

我在状态更改时自动重新渲染视图时遇到问题。 状态已更改,但未调用 render()。但是当我调用 this.forceUpdate() 时,一切正常,但我认为这不是最好的解决方案。 有人可以帮我吗?

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

你不应该直接变异 this.state。你应该使用 this.setState 方法。

更改loadItems

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

More in react docs

当您声明初始状态时,您应该从构造函数中使用 this.state = {};(就像在您的 loadItems() 方法中一样)。当您要更新项目时,请使用 this.setState({})。例如:

constructor() {
    super();

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

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

并更新您的 componentDidMount:

Store.addChangeListener(() => { this.reloadItems(); });

在您的组件中,每当您直接操作状态时,您需要使用以下内容:

this.setState({});

完整代码:

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