react生态redux
# 基本使用
yarn add redux
- action、action-creator
- reduce
- store
acion
{
type:"add",
payload:10
}
const actionCreate = payload=>{
return {
type:'add',
payload
}
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
reducer
const reducer = (prevState,action)=>{
return newState
}
const reducer = (state,action)=>{
switch(action.type){
case 'add':
return ;
case 'remove':
return ;
default:
return state
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
store
const store = createStore(reducer)
store.dispatch(action)
const state = store.getState()
const unSubscribe = store.subscribe(()=>{
console.log(store.getState())
})
unSubscibe()
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# react-redux
React-Redux :React接入Redux
使用 hooks 的写法
yarn add react-redux导入
Provider组件 :import {Provider} from "react-redux"包裹整个应用程序
<Provider store={store}> <App/> </Provider>1
2
3设置好store的值
useSelector
相当于 :store.getState()
import {useSelector} from "react-redux"
const count = useSelector (state=>state.list)
1
2
2
useDispatch
相当于:store.dispatch(action)
import {useDispatch} from "react-redux"
const dispatch = useDiapatch()
dispatch(action)
1
2
3
4
5
2
3
4
5
# 项目结构
推荐使用的 redux 管理结构
- store
- actions //创建 actions
- reducers // 创建 reducers
- index.js //创建 store
1
2
3
4
2
3
4
集中管理 ActionType ——利于维护项目
使用 domain/action(功能/动作) 进行分类处理
- 创建
actionType目录 - 声明
actiontype并导出 - 使用
const add = "counter/add"
const remove = "conter/remove"
export {add,remove}
1
2
3
4
2
3
4
import * as types = ""
type: types.add
//...
1
2
3
2
3
拆分 Reducer
combineReducers 函数
import {combineReducers} from 'redux'
const aRuducer = ()=>{}
const bRuducer = ()=>{}
const rootReducer = combineReducers({
a: aReducer,
b: bReducer
})
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# redux中间件
rudux-logger
import {createStore,applyMiddleWare} from 'redux'
import logger from 'redux-logger'
import rootReducer from './reducers'
const store = createStore(rootReducer,applyMiddleware(logger))
1
2
3
4
5
2
3
4
5
redux-thunk
处理异步操作
使用 redux-thunk 中间件后,action 既可以是对象,也可以是函数
const funAsync = ()=>{
return (dispatch,getState)=>{
//...Async
}
}
dispatch(funAsync())//函数
1
2
3
4
5
6
2
3
4
5
6
import thunk from 'redux-thunk'
const store = createStore(rootReducer,applyMiddleware(thunk,logger))
//使用 index.js
export const funAysnc = ()=>{
return (dispatch)=>{
setTimeout(()=>{
},1000)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# redux-devtools-exension
import thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
const store = createStore(reducer, composeWithDevTools(applyMiddleware(thunk)))
export default store
1
2
3
4
5
6
2
3
4
5
6
编辑 (opens new window)
上次更新: 2023/02/07, 15:11:55