[英]Why react doesn't call render when state is changed?
当状态改变时,我有自动重新渲染视图的问题。 状态已更改,但不调用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(); });
你this.state
直接改变this.state
。 您应该使用this.setState
方法。
更改loadItems
:
loadItems() {
this.setState({
todos: Store.getItems()
});
}
在组件中,无论何时直接操作状态,都需要使用以下命令:
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");
//...
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.