You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hey, @zerofront, didn't pick up on this for a while. Sorry!
Too Long; Didn't Read
setState is a React class component built-in feature.
When you pass new state values to it, the component obeys that change and rerenders its elements accordingly. It's as simple as that.
trySetState is a feature by this manager utility, built on top of that React feature.
It attempts to read your props and find out whether a key of the same name exists, and if it does, only changes the state value if you don't provide a prop of the same name for it. If your prop name is value and your state name is value, then trySetState will attempt to use prop.value to update your state.value.
The Longer Explanation
classNumberextendsReact.Component{state={number: this.props.number||0};// defaults to 0trySetState=NumberAutoControlledManager.trySetState;incrementNumber=()=>{this.setState({// <-- Updates "number"; Doesn't care if props also has "number".number: this.state.number+1,});}incrementNumberIfNoProp=()=>{this.trySetState({// <-- Updates "number" state only if prop.number wasn't given.number: this.state.number+1});}}// The number will increment itself since AppUncontrolled didn't give a prop.constAppUncontrolled=<div><Number/></div>;// Starts at 0. Increments by 1 on every button click.// The number will not increment because AppControlled gave it `123`.constAppControlled=<div><Numbernumber={123}/></div>;// Starts at 123. Never increments.
The idea of this utility is to help you write components that update themselves if you provide no props for them.
Don't get me wrong: You could do the same thing without this utility, but you'll have to write the implementation details yourself... on every component that can self-update. Or you could write your own. How you do it is a matter of personal choice.
what's the difference between setState and trySetSate?
The text was updated successfully, but these errors were encountered: