Created
August 30, 2018 14:40
-
-
Save rikwatson/7c91ff983bae5c2373b4c5271a687f1e to your computer and use it in GitHub Desktop.
Using a separate object to handle state in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import ReactDOM from "react-dom"; | |
import "./styles.css"; | |
const actions = { | |
init() { | |
return { value: 0 }; | |
}, | |
increment(state) { | |
return { value: state.value + 1 }; | |
}, | |
decrement(state) { | |
return { value: state.value - 1 }; | |
} | |
}; | |
class App extends React.Component { | |
state = actions.init(); | |
handleIncrement = () => { | |
this.setState(actions.increment); | |
}; | |
handleDecrement = () => { | |
this.setState(actions.decrement); | |
}; | |
render() { | |
return ( | |
<div> | |
<h2>{this.state.value}</h2> | |
<button onClick={this.handleIncrement}>+</button> | |
<button onClick={this.handleDecrement}>-</button> | |
</div> | |
); | |
} | |
} | |
const rootElement = document.getElementById("root"); | |
ReactDOM.render(<App />, rootElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From here
Note that all state information is maintained in
actions
.