1.react-redux的使用
index.js引入Provider
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
import store from './redux/store'
import { Provider } from 'react-redux'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
)
在App.js使用容器组件connect
import {connect} from 'react-redux';
//在函数中结构使用
const {changeCity,city,getList,list} = props
//容器高阶组件的使用
const getList = ()=>{ //发起异步请求
return (dispatch)=>{
setTimeout(()=>{
dispatch({
type:'list',
value:[2,3,4,5,6,4,3]
})
},500)
}
}
const mapDispatchToProps = {
changeCity(){
return{
type:"cxk",
value:'赣州'
}
},
getList
}
const mapStateToProps = (state) => {
console.log(state)
return{
city:state.cityReducer,
list:state.listReducer
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
2.redux-persist 持久化
store.js
import { createStore,combineReducers,applyMiddleware } from "redux";
import thunk from 'redux-thunk';
//引入redux-persist进行持久化
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage'
const persistConfig = {
key: 'root',
storage,
whitelist: ['cityReducer'] //白名单,只允许某项持久化
}
//处理持久化store
const reducer = combineReducers({ //合并两个reducer
cityReducer,
tabReducer,
listReducer
})
const persistedReducer = persistReducer(persistConfig, reducer)
const store = createStore(persistedReducer,applyMiddleware(thunk)); //创建一个store
let persistor = persistStore(store)
export {
store,
persistor
}
index.js
import {store,persistor} from './redux/store'
import { Provider } from 'react-redux'
import { PersistGate } from 'redux-persist/integration/react'
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<App />
</PersistGate>
</Provider>