2016-09-23 6 views
1

理由がありますか?setStateは再レンダリングするために実行されませんか?私はconsole.logコールバックを使用して、状態が変更されたかどうかを検出しましたが、役に立たないことはありません。ReactJS setStateがチェックボックスの最初のトグルで動作しない

ここに私が使用しているコードがあります。関数呼び出しの状態はboolですが、関数の基本はここにあります。

export class ExampleClass extends React.Component { 
constructor(props) { 
    super(props); 
    this.state = { 
     usingToggleOne: false 
    }; 
    } 
} 
toggleforToggleOne(event) { 
    this.setState({ 
    usingToggleOne: !this.state.usingToggleOne, 
    }); 
} 

render() { 
    return(
    <input type="checkbox" 
        onChange={this.toggleforToggleOne.bind(this)} /> 
} 

最初にチェックボックスをオンにしてもチェックが入りますが、状態は変更されませんが、正常に動作した後に表示されます。理由は何ですか?私はObject.assignを使って最初のチックを得るのに運が良かったのですが、それは状態を突然変異させているからです。

答えて

1

render()に以下のコードでは、これcodepenで示されているようcomponentDidUpdate()方法でconsole.log()を試してみてください。http://codepen.io/PiotrBerebecki/pen/ZpLNZd

することもできますアクセス「SETSTATE」に渡されるオプションのコールバック関数を使用して新しい状態。詳細はこちらhttp://reactkungfu.com/2016/03/dive-into-react-codebase-handling-state-changes/#solving_the_validation_problem

boolは、ボックスにチェックを入れたり、アンティッキされたりするたびに変わります。

はまた、リアクトドキュメントから、次の点に注意してください。パフォーマンスの向上のためにバッチ処理することができるSETSTATEとの通話への呼び出しの同期動作の保証はありません https://facebook.github.io/react/docs/component-api.html#setstate

。 shouldComponentUpdate()で条件付きレンダリングロジックが実装されていない限り、setState()は常に再レンダリングをトリガーします。変更可能なオブジェクトが使用されていて、shouldComponentUpdate()でロジックを実装できない場合、新しい状態が以前の状態と異なる場合にのみsetState()を呼び出すと、不必要な再レンダリングが回避されます。

class ExampleClass extends React.Component { 
    constructor() { 
    super(); 
    this.state = { 
     usingToggleOne: false 
    }; 

    } 

    toggleforToggleOne(event) { 
    console.clear(); 
    console.log('check in toggle before set state', this.state.usingToggleOne); 
    this.setState({ 
     usingToggleOne: !this.state.usingToggleOne 
    }, function afterStateChange() {this.useNewState();}); 
    console.log('check in toggle after set state', this.state.usingToggleOne); 
    } 

    useNewState() { 
    console.log('check in useNewState callback', this.state.usingToggleOne); 
    } 

    componentWillUpdate() { 
    console.log('check in componentWillUpdate', this.state.usingToggleOne); 
    } 

    componentDidUpdate() { 
    console.log('check in componentDidUpdate', this.state.usingToggleOne); 
    } 

    render() { 
    console.log('check in render', this.state.usingToggleOne); 
    return(
     <input type="checkbox" 
      onChange={this.toggleforToggleOne.bind(this)} /> 
    ); 
    } 
} 
+1

興味深い!だから私はレンダリングでそれを呼び出し、正しい状態を返していますが、レンダリング前の状態を 'componentWillUpdate'で呼び出していますが、正しくない状態になっています。 – kermitvomit

+1

よく目撃された!私はこれを説明するために私の答えにさらなる情報を加えました。 –

+1

オハイオ州それはなぜ問題があるのか​​についてより多くの意味がある。 これをさらに調べてみると、 'LinkedStateMixin'が解決策であるようです。ありがとう:) 編集:それはすでに廃止されているようだ、私は双方向バインディングを推測する? – kermitvomit

関連する問題