🚀🚀首发:CSDN碰磕,学无止境
🌞🌞🌞晴28°
??Better to light one candle than to curse the darkness.
📅2022/6/22
React-Redux
安装
npm i react-redux
使用
主要使用:connect 与 Provider 配合
完美替换了dispatch 和subscribe
🌼1.在入口文件将显示的内容使用provider包裹
并且传递store从而公共使用
<Provider store={store}>
<Zhuye2 />
</Provider>
🌼2.在组件中通过connect进行通信订阅
connect (将来给孩子传的属性,将来给孩子传的回调函数)
使用前不要忘记引入
import { connect } from 'react-redux';
export default connect((state)=>{
console.log(state)
return{
isShow:state.TabbarReducer.isShow
}
})(Zhuye2)
根据之前的案例在NotFound 组件中进行通知
export default connect(null,{
hide(){
return{
type:"404传的消息",
isShow:false
}
},
show(){
return{
type:"404传的消息",
isShow:true
}
}
})(NotFound)
通过props .函数名进行调用…
import React, { useEffect } from 'react';
import { connect } from 'react-redux';
function NotFound(props){
useEffect(()=>{
console.log(props)
props.hide()
return()=>{
console.log("销毁...");
props.show()
}
},[])
return (
<div>
404
</div>
);
}
export default connect(null,{
hide(){
return{
type:"404传的消息",
isShow:false
}
},
show(){
return{
type:"404传的消息",
isShow:true
}
}
})(NotFound)
这样就完美替换了dispatch
redux持久化(redux-persist)
官网:[redux-persist - npm (npmjs.com)](redux-persist - npm (npmjs.com))
安装
npm i redux-persist
使用
store.js中
import {applyMiddleware, combineReducers, createStore,compose} from 'redux';
import CinemaListReducer from './reducers/CinemaListReducer';
import CityReducer from './reducers/CityReducer';
import TabbarReducer from './reducers/TabbarReducer';
import reduxThunk from 'redux-thunk'
import reduxPromise from 'redux-promise'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage'
const persistConfig = {
key: 'pengke',
storage,
whitelist:['CityReducer']
}
const reducer=combineReducers({
CityReducer,
TabbarReducer,
CinemaListReducer
})
const persistedReducer = persistReducer(persistConfig, reducer)
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(persistedReducer,composeEnhancers(applyMiddleware(reduxThunk,reduxPromise)))
let persistor = persistStore(store);
export{
store,
persistor
}
在之前的案例上做改变
引入----定义本地存储-----persistReducer增强----persistStore(store)—导出(store,persistor)
Tip :whitelist:设置只持久化的(白名单)
这样就实现了redux的持久化🆗
|