2016-03-23 7 views
2

状態が変更されたときに自動的に表示を再描画することに問題があります。 状態は変更されましたが、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"); 
    //... 
}} 

答えて

8

あなたは初期状態を宣言しているコンストラクタから(自分のloadItems()方法のように)this.state = {};を使用する必要があります。アイテムを更新する場合は、this.setState({})を使用してください。あなたのコンポーネントで

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

'this.state' sh ouldは直接突然変異することはありません。 – jered

+0

@JCD私の間違いは、React Nativeから来ていますが、 'this.state = {}'を使ってコンストラクタから初期状態を宣言することができます。 –

+4

@JCD実際には、[React docs](https://facebook.github.io/react/docs/reusable-components.html)によると、これは完全に正当なものであり、少なくともそこに使用されています(「ES6 Classes in 2番目のコードブロック) –

7

this.stateを直接変更してはいません。 this.setStateメソッドを使用する必要があります。

変更loadItems

loadItems() { 
    this.setState({ 
     todos: Store.getItems() 
    }); 
} 

More in react docs

0

、あなたが直接あなたが以下を使用する必要がある状態を操作するたびに:

constructor() { 
    super(); 

    this.state = { 
     todos: Store.getItems() 
    }; 
} 

reloadItems() { 
    this.setState({ 
     todos: Store.getItems() 
    }); 
} 

とあなたのcomponentDidMountを更新します。たとえば

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"); 
    //... 
}} 
関連する問題