Redux
redux是React技术栈使用最为广泛的状态管理
怎么学习Redux
记住“三个三” 第一个“三”(3个api):createStore、combineReducers、applyMiddleware 第二个“三”(3个特点):单一数据源、store只读、使用reducer纯函数修改store 第三个“三”(3个概念):State、Action、Reducer
安装Redux
npm i redux react-redux -S
Redux的简单案例
redux的状态管理配置
import {
createStore
} from 'redux'
const initState = {
msg: 'hello Redux',
num: 1
}
function reducer(state=initState,action){
const {type,payload} = action
const newState = JSON.parse(JSON.stringify(state))
switch(type){
case 'add':
newState.num += payload
break;
...
}
return newState
}
const store = createStore(reducer)
当一个项目需要分多个子store时
import { crecreateStoreat,combineReducers } from 'redux'
import user from '/user'
const reducer = combineReducers({user,...})
const store = createStore(reducer)
export default store
引入redux状态管理
import React from 'react';
import {Provider} from 'react-redux';
import store from './store';
function App() {
return (
<Provider store={store}>
<T />
</Provider>
);
}
export default App;
redux状态管理 在JSX组件中的使用
import React from 'react';
import { connect } from 'react-redux';
export default connect(
(state) => {
return { state }
},
(dispath) => ({
add: payload => dispath({ type: 'add', payload })
})
)((props) => {
const { state, add } = props
return (
<div>
<h1>Redux的简单测试</h1>
<h3>{state.reducer.num}</h3>
<button onClick={() => add(1)}>自增+1</button>
<button onClick={() => add(2)}>自增+2</button>
<button onClick={() => add(-1)}>自增-1</button>
</div>
)
})
使用HOOK语法
import React from "react";
import { useSelector, useDispatch } from "react-redux";
export default () => {
const state = useSelector(state => state)
const dispatch = useDispatch()
console.log(state);
console.log(dispatch);
return (
<>
<h1>使用Hook方式使用React</h1>
<h3>{state.reducer.num}</h3>
<button onClick={() => dispatch({type:'add',payload:1})}>自增+1</button>
<button onClick={() => dispatch({type:'add',payload:2})}>自增+2</button>
<button onClick={() => dispatch({type:'add',payload:-1})}>自增-1</button>
</>
)
}
深复制库
我们在之前的jsx中使用的深复制是JSON.parse(JSON.stringify( )) 这个虽然能实现store中state的深复制,但是其效率不高。因此,我们可以使用immer包进行深复制。
npm i immer -S
immer使用方法
对之前的jsx配置进行修改
import {
createStore,
combineReducers
} from 'redux'
import produce from 'immer';
const initState = {
msg: 'hello Redux',
num:1
}
function reducer(state = initState, action) {
const {
type,
payload
} = action
return produce(state,(newState)=>{
switch (type) {
case 'add':
newState.num +=payload
break;
}
})
}
const reducers = combineReducers({
reducer
})
const store = createStore(reducers)
export default store
装饰器语法
由于装饰器语法还未被W3C支持,因此我们需要安装babel插件用于解析装饰器
npm i @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties -D
再在babel配置中引用插件
{
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }],
["@babel/plugin-proposal-class-properties"]
]
}
|