Open timqian opened 7 years ago
state ==[auto update]==> view ^ | [update] |
---|
action
// https://jsbin.com/fumerup/edit?js,output
import { observer } from 'mobx-react'
import { observable, action } from 'mobx'
class TickerStore {
@observable time = 0
@action incr = () => {
this.time += 1
}
@action desc = () => {
this.time -= 1
}
}
const Ticker = observer(({ tickerStore }) => (
<div>
<span>tick {tickerStore.time} times</span>
<button onClick={tickerStore.incr}>+</button>
<button onClick={tickerStore.desc}>-</button>
</div>
))
const tickerStore = new TickerStore()
ReactDOM.render(<Ticker tickerStore={tickerStore} />, document.querySelector('#app'))
The whole state of your app is stored in an object tree inside a single store. The only way to change the state tree is to emit an action, an object describing what happened. To specify how the actions transform the state tree, you write pure reducers.
// https://github.com/jackielii/simplest-redux-example/blob/master/index.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import { Provider, connect } from 'react-redux'
// React component
class Counter extends Component {
render() {
const { value, onIncreaseClick } = this.props
return (
<div>
<span>{value}</span>
<button onClick={onIncreaseClick}>Increase</button>
</div>
)
}
}
Counter.propTypes = {
value: PropTypes.number.isRequired,
onIncreaseClick: PropTypes.func.isRequired
}
// Action
const increaseAction = { type: 'increase' }
// Reducer
function counter(state = { count: 0 }, action) {
const count = state.count
switch (action.type) {
case 'increase':
return { count: count + 1 }
default:
return state
}
}
// Store
const store = createStore(counter)
// Map Redux state to component props
function mapStateToProps(state) {
return {
value: state.count
}
}
// Map Redux actions to component props
function mapDispatchToProps(dispatch) {
return {
onIncreaseClick: () => dispatch(increaseAction)
}
}
// Connected Component
const App = connect(
mapStateToProps,
mapDispatchToProps
)(Counter)
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
React basic concepts