簡體   English   中英

當狀態改變時,為什么反應不會調用渲染?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM