using setstate in child component code example
Example 1: pass setstate to child
//ChildExt component
class ChildExt extends React.Component {
render() {
return (<div><button onClick={() => this.props.handleForUpdate('someNewVar')}>Push me</button></div>
)}
}
//Parent component
class ParentExt extends React.Component {
constructor(props){
super(props);
this.state = {lol: false }
}
handleForUpdate(someArg){
this.setState({lol: true});
console.log(someArg);
}
//Notice how we don't pass the arguments into the bind.this even though it does take an argument.
render() {
return (<ChildExt handleForUpdate={this.handleForUpdate.bind(this)} />)
}
}
Example 2: react setState
incrementCount() {
// Note: this will *not* work as intended.
this.setState({count: this.state.count + 1});
}
handleSomething() {
// Let's say `this.state.count` starts at 0.
this.incrementCount();
this.incrementCount();
this.incrementCount();
// When React re-renders the component, `this.state.count` will be 1, but you expected 3.
// This is because `incrementCount()` function above reads from `this.state.count`,
// but React doesn't update `this.state.count` until the component is re-rendered.
// So `incrementCount()` ends up reading `this.state.count` as 0 every time, and sets it to 1.
// The fix is described below!
}