javascript - 为什么状态改变时 react 不调用渲染?

标签 javascript reactjs flux

我在状态更改时自动重新渲染 View 时遇到问题。 状态已更改,但未调用 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 = {};(就像在您的 loadItems() 方法中一样)。当您想要更新项目时,请使用 this.setState({})。例如:

constructor() {
    super();

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

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

并更新你的componentDidMount:

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

关于javascript - 为什么状态改变时 react 不调用渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36185577/

相关文章:

javascript - 为具有核心和子模块的应用程序构建 Webpack

javascript - 使用js更新表单字段但未在提交的数据中显示

javascript - react 上下文不更新

reactjs - 使用 Storyshots 渲染 React Portal 时出错

aggregate - 具有连续计数器的流入聚合窗口

javascript - react : Removing a class styling after componentWillUpdate

javascript - 带有 MVC 3 和 ViewModel 的 Backbone.js

javascript - 从 javaScript 数组中删除 HTML 代码?

javascript - 当 jQueryUI 对话框没有 ID 时打开它

reactjs - 暂时上传到 S3 上,如果不使用就删除?