Tài liệu¶
Cài đặt source code.
Giải thích:
Action:
import * as types from '../constants/ActionTypes'; export function add() { return { type: types.ADD }; }
Mô tả hành động .
Reducer:
Ta sẽ có countReducer, có nhiệm vụ biến đổi state sau khi nhận được action add:
import {ADD} from '../constants/ActionTypes'; // initialState const initialState = { 'count': 0 } export default function countReducer(state = initialState, action) { switch (action.type) { case ADD: return { ...state, 'count' : state.count + 1 } default: return state; } }
Combine reducer vào root reducer:
import { combineReducers } from 'redux'; import countReducer from './countReducer'; const rootReducer = combineReducers({ countReducer }); export default rootReducer;
Khởi tạo store:
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import * as serviceWorker from './serviceWorker'; import {Provider} from "react-redux"; import { createStore, applyMiddleware } from 'redux'; import { createLogger } from 'redux-logger'; import CountExample from './components/CountExample'; import rootReducer from './reducers/rootReducer'; // initialState const initialState = {} // Create store const store = createStore( rootReducer, initialState, applyMiddleware( createLogger() ) ); ReactDOM.render( <Provider store={store}> <div> <CountExample /> </div> </Provider>, document.getElementById('root') ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
Trong componet, map state của redux với props, map dispatch của redux với action props:
import React, { Fragment, Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as CountActions from '../actions/CountActions'; class CountExample extends Component { render() { const { actions, count } = this.props; return ( <Fragment> <div> <button onClick={actions.add}>Increase</button> </div> <div> { count } </div> </Fragment> ); } } function mapStateToProps(state) { return { count: state.countReducer.count }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(CountActions, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(CountExample);