Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@BTMPL
Created April 17, 2017 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BTMPL/81cae986bd93b8c55255e3d110e7efb5 to your computer and use it in GitHub Desktop.
Save BTMPL/81cae986bd93b8c55255e3d110e7efb5 to your computer and use it in GitHub Desktop.
Understanding setState
// assuming this.state = { value: 0 }
this.setState({
value: 1
});
console.log(this.state.value); // 0
// assuming this.state = { value: 0 };
this.setState({ value: this.state.value + 1});
this.setState({ value: this.state.value + 1});
this.setState({ value: this.state.value + 1});
// assuming this.state = { value: 0 };
this.setState((state) => ({ value: state.value + 1}));
this.setState((state) => ({ value: state.value + 1}));
this.setState((state) => ({ value: state.value + 1}));
render() {
return <button onClick={this.inc}>Click to update</button>
}
inc() {
console.log('before: ' + this.state.test);
this.setState({
test: this.state.test+1
});
console.log('after: ' + this.state.test);
}
// click!
before: 1
after: 1
// click!
before: 2
after: 2
class Component extends React.Component {
constructor(props) {
super(props);
this.state = { value: this.props.value };
}
render() {
return <div>The value is: {this.state.value}</div>
}
}
class Component extends React.Component {
constructor(props) {
super(props);
this.state = { value: this.props.value };
}
componentWillReceiveProps(nextProps) {
if(nextProps.value !== this.props.value) {
this.setState({value: nextProps.value});
}
}
render() {
return <div>The value is: {this.state.value}</div>
}
}
this.setState((state) => {
if(checkSomeConditions()) return undefined;
else return { value: 42}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment