一、Redux的安装
npm install redux
二、Redux的核心
1、action
动作对象 属性 type:标识,值为字符串、唯一,必要。data:数据,值类型不限,可选 例子: const action = {type: ‘ADD_COUNT’, data: 888} 提交action store.dispatch( action )
2、reducer
用于初始化状态,修改状态 是根据旧的state和action,生成新的state的一个纯函数
3、store
将state、action、reducer联系在一起的对象
二、Redux的简单使用
创建action
const ADD_COUNT= ( data) = > {
return { type: 'ADD_COUNT' ,
data: data
}
}
const REDUCE_COUNT= ( data) = > {
return {
type: 'REDUCE_COUNT' ,
data,
}
}
export { ADD_COUNT, REDUCE_COUNT} ;
创建reducer
function reducer ( count= 10 , action) {
const { type, data} = action;
switch ( type) {
case 'ADD_COUNT' :
return count + data
case 'REDUCE_COUNT' :
return count- data
default :
return count;
}
}
export default reducer;
创建store
import { createStore} from 'redux'
import reducer from 'count_reducer'
const store = createStore ( reducer) ;
export default store;
绑定到项目根结点
< Provider store= { store} >
< App / >
< / Provider>
组件中使用
const state = store. getState ( )
console. log ( state. count)
store. dispatch ( ADD_COUNT ( 12 ) )
store. dispatch ( REDUCE_COUNT ( 12 ) )
store. subscribe ( ( ) = > {
console. log ( store. getState ( ) )
} )
let unsubscribe = store. subscribe ( ( ) = >
console. log ( store. getState ( ) )
) ;
unsubscribe ( ) ;
三、React-Redux的使用
安装依赖包
npm install react- redux
@reduxjs/toolkit (简化书写样式)
npm install @reduxjs/ toolkit
创建reducer
import { createSlice} from '@reduxjs/toolkit' ;
import axios from "axios" ;
const testStore = createSlice (
{
name: 'test' ,
initialState: {
testList: [ ]
} ,
reducers: {
setTestList ( state, action) {
state. testList = action. payload
}
}
}
)
const { setTestList} = testStore. actions
const getTestList = ( ) = > {
return async ( dispatch) = > {
const res = await axios. get ( '' )
dispatch ( setTestList ( res. data) )
}
}
export { geteTestList, setTestList}
const reducer = testStore. reducer
export default reducer
创建store
import { configureStore } from '@reduxjs/toolkit'
import testReducer from './modules/testStore'
const store = configureStore ( {
reducer: {
bill: testReducer
}
} )
export default store
绑定到项目根结点
< Provider store= { store} >
< App / >
< / Provider>
组件中获取
import { useSelector } from 'react-redux'
const Demo = ( ) = {
const testList = useSelector ( state= > state. test. testList)
console. log ( testList )
return (
< > < div> Demo< / div> < / >
)
}
组件中修改
import { useDispatch } from 'react-redux'
import getTestList from './modules/testStore'
const Demo = ( ) = {
const dispatch = useDispatch ( )
useEffect ( ( ) = > {
console. log ( 'ee' )
dispatch ( getTestList ( ) )
} , [ dispatch] )
return (
< > < div> Demo< / div> < / >
)
}