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

编程入门 行业动态 更新时间:2024-10-09 11:22:41
本文介绍了为什么当状态改变时反应不调用渲染?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

推荐答案

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

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

并更新您的componentDidMount:

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

更多推荐

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

本文发布于:2023-11-13 11:30:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584240.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:状态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!