私はReact.jsの初心者です。 Reactのライフサイクルを理解しようとしているうちに、私はcomponentWillReceivePropsを見つけました。私は他の機能を持っているにもかかわらず、私はまだcomponentWillReceivePropsを理解することができません。私はすべてのボタンをクリックすると、私は変数 'val'をインクリメントしている小さなスニペットを作成しました。 valが5の倍数になったとき、私は '増加'の値を変更したい、それはできない。React testing 'componentWillReceiveProps'
私のコードは次のとおりです。
var Increment = React.createClass({
getInitialState: function() {
return {val: 0, increasing: false};
},
componentWillMount: function() {
console.log("componentWillMount");
},
componentDidMount: function() {
console.log("componentDidMount");
},
handleClick: function() {
console.log("inHandleClick");
console.log(this.state.val);
this.setState({val: (this.state.val+1)});
},
componentWillReceiveProps : function(nextProps) {
this.setState({
increasing: (nextProps.val > this.props.val)
});
},
shouldComponentUpdate: function(nextProps, nextState) {
return (nextState.val % 5 ==0)
},
render: function() {
console.log(this.state.increasing);
return (
<div>
<button onClick={this.handleClick}>{this.state.val}</button>
</div>
);
}
});
ReactDOM.render(<Increment />, mountNode);
どれリード?事前
あなたのケースでは、小道具が変更されておらず、状態のみが変化しているため、 'componentWillReceiveProps'は呼び出されていません。おそらく、あなたは 'componentWillUpdate'を使うつもりでしたか?これは小道具や状態が変わると呼び出されます。 – Aaron
アーロン...あなたは私の例を助けてくれますか? –
@SukhmeetSingh私はあなたがReactの状態と小道具の違いに混乱していると信じています。 [this](http://stackoverflow.com/questions/27991366/what-is-the-difference-between-state-and-props-in-react) – Calvin