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

时间:2016-03-23 18:06:32

标签: javascript reactjs flux

当状态发生变化时,我有自动重新渲染视图的问题。 状态已更改,但未调用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");
    //...
}}

3 个答案:

答案 0 :(得分:8)

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

constructor() {
    super();

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

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

并更新您的componentDidMount

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

答案 1 :(得分:7)

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

更改loadItems

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

More in react docs

答案 2 :(得分:0)

在您的组件中,无论何时直接操作状态,都需要使用以下内容:

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");
    //...
}}
相关问题