Redux 的的概念可以看我这篇笔记:Redux - Redux Essentials(官网)
一、Redux
1. 核心概念
- Reducer
- Store
- Action 及 Action Creator
- getState 及 State Selector
2. 目录结构
一个 App 我会这样写,目录结构如下
/App
/reducers
userReducer.js
canvasReducer.js
/store
store.js
// userReducer.js
const initialState = {
login: false,
vipType: 0
}
const userAction = (type, payload) => {
return {
type,
payload
}
}
const userReducer = ({state = initialState, action}) => {
let newState = {...state}
switch (action.type){
case 'user/login':
newState.login = true
return newState
case 'user/logout':
newState.login = false
case 'user/vipType':
newState.vipType = action.payload
return newState
default:
return state
}
}
export { userReducer, userAction }
// canvasReducer
const initialState = {
width: 500,
height: 500
}
const canvasAction = (type,payload) => {
return {
type,
payload
}
}
const canvasReducer = ({state,action}) => {
let newState = {...state}
switch (action.type){
case 'canvas/size':
newState = action.payload.width
newState = action.payload.height
return newState
default:
return state
}
}
export { canvasReducer, canvasAction }
// store.js
import { createStore, combineReducers } from 'redux'
import { userReducer } from './userReducer'
import { canvasReducer } from './canvasReducer'
const store = createStore(combineReducers({
user: userReducer,
canvas: canvasReducer
}))
const userSelector = () => {
return store.getState().user
}
const canvasSelector = () => {
return store.getState().canvas
}
export {
store,
userSelector,
canvasSelector
}
二、react-redux 库
react-redux 新增了两个 API
- provider
- connect
「@浪里淘沙的小法师」