我在状态更改时自动重新渲染 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/