react redux diagram
view觸發事件->dispatch發送action->reducer根據action返回新的state->store接受state更新->更新view
actions純js物件,包含type讓reducer判斷處理其於由使用者自訂。
src/action.js
export const INCREMENT = () => {
return {
type: 'INCREMENT',
count: 1
}
};
export const DECREMENT = () => {
return {
type: 'DECREMENT',
count: -1
}
};
Counter Component
mapStateToProps:接受由reducer傳來的state
mapDispatchToProps:接收dispatch參數(dispatch為Store的方法),定義發送事件的方法
connect:把component與store串在一起,所以state可以轉成props傳遞下去
src/Counter.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import * as actions from './actions';
import { connect } from 'react-redux';
class Counter extends React.Component {
render () {
const { count, onClickPlus, onClickMinus } = this.props;
return (
<div>
<p><span>Count: {count}</span></p>
<div>
<button onClick={onClickPlus}>+1</button>
<button onClick={onClickMinus}>-1</button>
</div>
</div>
);
}
}
Counter.propTypes = {
count: PropTypes.number.isRequired,
onClickPlus: PropTypes.func.isRequired,
onClickMinus: PropTypes.func.isRequired
};
function mapStateToProps (state) {
return {
count: state.count
};
}
function mapDispatchToProps (dispatch) {
return {
onClickPlus: () => dispatch(actions.INCREMENT()),
onClickMinus: () => dispatch(actions.DECREMENT())
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Counter);
reducer產生新的state回傳
src/reducer.js
export default (state = {count: 0}, action) => {
let count = state.count;
switch (action.type) {
case 'INCREMENT':
return {count: count + action.count};
case 'DECREMENT':
return {count: count + action.count};
default:
return state;
}
}
Provider提供store給所有的component
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider, connect } from 'react-redux';
import reducer from './reducer';
import Counter from './Counter';
let store = createStore(reducer);
ReactDOM.render(
<Provider store={store}>
<Counter />
</Provider>,
document.getElementById('app')
);
github repositories react-redux-counter
https://github.com/kwon44/react-redux-counter
參考資料
Redux
https://redux.js.org/