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

Joz*_*ipa 2 javascript flux reactjs

当状态改变时,我有自动重新渲染视图的问题.国家已被改变,但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");
    //...
}}
Run Code Online (Sandbox Code Playgroud)

Jos*_*que 8

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

constructor() {
    super();

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

reloadItems() {
    this.setState({
        todos: Store.getItems()
    });
}
Run Code Online (Sandbox Code Playgroud)

并更新你的componentDidMount:

Store.addChangeListener(() => { this.reloadItems(); });
Run Code Online (Sandbox Code Playgroud)

  • @JCD实际上,根据[React docs](https://facebook.github.io/react/docs/reusable-components.html),这是完全合法的,或至少它在那里使用(参见ES6中的类第二个代码块) (4认同)

小智 7

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

变化loadItems:

loadItems() {
    this.setState({
        todos: Store.getItems()
    });
}
Run Code Online (Sandbox Code Playgroud)

更多反应文档