为什么当状态改变时反应不调用渲染? [英] Why react doesn't call render when state is changed?
本文介绍了为什么当状态改变时反应不调用渲染?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
状态更改时,我无法自动重新渲染视图.
状态已更改,但未调用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(); });
这篇关于为什么当状态改变时反应不调用渲染?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文