Reputation: 405
I am trying to build a credit card information form.
Looking at all the react code out there makes me feel like I should be doing this
getInitialState: function() {
return {
number: card.number,
exp_month: card.exp_month,
cvc: card.cvc
error: card.error
};
}
essentially cloning part of my store. what are the downsides of just doing
getInitialState: function() {
return card;
}
Is it a concern the card could change without react knowing? Wouldn't I have event handlers that setState when card data changes anyway?
Upvotes: 1
Views: 74
Reputation: 1608
You can do this but I wouldn’t recommend it. Your code will be clearer when you show what the initial state looks like. A little explanation why it is possible to do though:
The docs on getInitialState (source):
The return value will be used as the initial value of this.state.
And under setState is mentioned (source):
NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
This implies that your card object is used once to define the state initially but that the state will lead a different life afterwards.
Upvotes: 3
Reputation: 4342
Should not be a problem, the getInitialState
is just called once the the component is mounted. To chagne the state, you still need to call the setState
function, changing the card
object won't help
Upvotes: 0