Redux 的的概念可以看我这篇笔记:Redux - Redux Essentials(官网)

一、Redux

1. 核心概念

  • Reducer
  • Store
  • Action 及 Action Creator
  • getState 及 State Selector

2. 目录结构

一个 App 我会这样写,目录结构如下

  1. /App
  2. /reducers
  3. userReducer.js
  4. canvasReducer.js
  5. /store
  6. store.js
  1. // userReducer.js
  2. const initialState = {
  3. login: false,
  4. vipType: 0
  5. }
  6. const userAction = (type, payload) => {
  7. return {
  8. type,
  9. payload
  10. }
  11. }
  12. const userReducer = ({state = initialState, action}) => {
  13. let newState = {...state}
  14. switch (action.type){
  15. case 'user/login':
  16. newState.login = true
  17. return newState
  18. case 'user/logout':
  19. newState.login = false
  20. case 'user/vipType':
  21. newState.vipType = action.payload
  22. return newState
  23. default:
  24. return state
  25. }
  26. }
  27. export { userReducer, userAction }
  1. // canvasReducer
  2. const initialState = {
  3. width: 500,
  4. height: 500
  5. }
  6. const canvasAction = (type,payload) => {
  7. return {
  8. type,
  9. payload
  10. }
  11. }
  12. const canvasReducer = ({state,action}) => {
  13. let newState = {...state}
  14. switch (action.type){
  15. case 'canvas/size':
  16. newState = action.payload.width
  17. newState = action.payload.height
  18. return newState
  19. default:
  20. return state
  21. }
  22. }
  23. export { canvasReducer, canvasAction }
  1. // store.js
  2. import { createStore, combineReducers } from 'redux'
  3. import { userReducer } from './userReducer'
  4. import { canvasReducer } from './canvasReducer'
  5. const store = createStore(combineReducers({
  6. user: userReducer,
  7. canvas: canvasReducer
  8. }))
  9. const userSelector = () => {
  10. return store.getState().user
  11. }
  12. const canvasSelector = () => {
  13. return store.getState().canvas
  14. }
  15. export {
  16. store,
  17. userSelector,
  18. canvasSelector
  19. }

二、react-redux 库

react-redux 新增了两个 API

  • provider
  • connect

「@浪里淘沙的小法师」