日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

react?redux及redux持久化示例詳解_React

作者:你華還是你華 ? 更新時(shí)間: 2022-10-02 編程語(yǔ)言

一、react-redux

react-redux依賴于redux工作。 運(yùn)行安裝命令:npm i react-redux

使用: 將Provider套在入口組件處,并且將自己的store傳進(jìn)去:

import FilmRouter from './FilmRouter/index'
import {Provider} from 'react-redux'
import store from './FilmRouter/views/redux/store';
ReactDOM.render(
    <Provider store={store}>
        <FilmRouter />
    </Provider>
    , document.getElementById('root')
);

然后在子組件導(dǎo)出的時(shí)候套一層connet組件,并且把父組件需要傳入的值傳入:

import React, { Component } from 'react'
import FRouter from './Router/ReactRouter'
import Tabbar from './components/Tabbar'
import { connect } from 'react-redux'
// import store from './views/redux/store'
// let unSubscribe
class Index extends Component {
  state = {
    // list: store.getState().TabbarReducer.list
  }
  // store.subscribe 訂閱
  componentDidMount() { 
    console.log(this.props)
    // store.subscribe(() => {
    //   console.log('訂閱', store.getState()) 
    //   this.setState({
    //     isShow: store.getState().TabbarReducer.flag
    //   })
    // })
    // unSubscribe = store.subscribe(() => {
    //   this.setState({
    //     list: store.getState().TabbarReducer.list
    //   })
    // })
  }
  // componentWillUnmount() {
  //   unSubscribe()
  // }
  render() {
    return (
        <div>
            <FRouter>
                {this.props.isShow && <Tabbar></Tabbar>}
            </FRouter>
        </div>
    )
  }
}
const mapStateToProps = (state) => {
  return {
    a: 1,
    b: 2,
    isShow: state.TabbarReducer.flag
  }
}
export default connect(mapStateToProps)(Index)

可以看到我們包了一層connect后把我們的reducer給傳入進(jìn)去,那在子組件中就可以直接使用this.props來獲取這個(gè)值來決定是否渲染了:

可以看到效果還是跟之前一樣,只不過采用了react-redux,那么我們?cè)贒etaile組件中就不用自己去分發(fā)dispatch事件了,將Details組件修改為:

import React, {useEffect} from 'react'
import { hide, show } from './redux/actionCreator/TabbarActionCreator'
// import store from './redux/store'
import {connect} from 'react-redux'
function Detaill(props) {
  console.log(props.match.params.filmId) // 第一種方式路由獲取參數(shù) 
//   console.log(props.location.query.filmId) // 第二種方式路由獲取參數(shù)  
//   console.log(props.location.state.filmId) // 第三種方式路由獲取參數(shù)  
  let {show, hide} = props
  useEffect(() => {
    console.log('創(chuàng)建')
    // store.dispatch(hide())
    hide()
    return () => {
      console.log('銷毀')
      // store.dispatch(show())
    show()
    }
  },[show,hide])
  return (
    <div>Detaill</div>
  )
}
const mapDispatchToProps = {
  show,
  hide
}
// connect接收兩個(gè)參數(shù),第一個(gè)是屬性,第二個(gè)是回調(diào)函數(shù)
export default connect(null, mapDispatchToProps)(Detaill);

可以看到這里都不需要我們?nèi)ispatch分發(fā)了,直接使用connect傳入到之前TabbarReducer寫好的類型以在子組件中以函數(shù)的形式去調(diào)用:

二、redux持久化

npm i redux-persist

修改store.js代碼:

import { applyMiddleware, combineReducers, createStore, compose } from "redux";
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' // defaults to localStorage for web
const persistConfig = {
    key: 'TabbarReducer',
    storage,
    // blacklist: ['TabbarReducer'] // navigation will not be persisted  黑名單
    whitelist: ['TabbarReducer'] // only navigation will be persisted  白名單
  }
const reducer = combineReducers({
    TabbarReducer
})
const persistedReducer = persistReducer(persistConfig, reducer)
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(persistedReducer, /* preloadedState, */ composeEnhancers(
    applyMiddleware(reduxThunk, reduxPromise)
));
let persistor = persistStore(store)
export {store, persistor}; 

然后在根組件中修改:

import FilmRouter from './FilmRouter/index'
import {Provider} from 'react-redux'
import {store, persistor} from './FilmRouter/views/redux/store';
import { PersistGate } from 'redux-persist/integration/react';
ReactDOM.render(
    <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
            <FilmRouter />
        </PersistGate>
    </Provider>
    , document.getElementById('root')
);

效果:

原文鏈接:https://juejin.cn/post/7128766881019723784

欄目分類
最近更新