亲宝软件园·资讯

展开

react-redux及redux状态管理工具使用详解

weixin_43993776 人气:0

react-redux使用及原理

1、下载 react-redux redux redux-thunk三个依赖包

yarn add react-redux  redux  redux-thunk

2、配置store对象,用来管理全局状态

import { createStore, combineReducers, applyMiddleware } from "redux"

// redux-thunk中间件,用来处理异步传值的方法
import reduxThunk from "redux-thunk"

import Reducer1 from "./reducer/Reducer1"
import Reducer2 from "./reducer/Reducer2"
import Reducer3 from "./reducer/Reducer3"

// combineReducers方法用来合并reducer,将reducer分开,便于管理
const reducer = combineReducers({
    Reducer1,
    Reducer2,
    Reducer3,
})

// 创建store对象,并将其暴露出去
const store = createStore( reducer, applyMiddleware(reduxThunk) )

export default store

3、创建reducer.js文件, reducer文件主要是用来处理改变store状态里面的值

const reducer1 = (prevState = { num: 10 }, action) => {
    let newState = { ...prevState }
    switch(action.type) {
        case "TYPE1":
            newState.num = action.value
            return newState
        default:
            return prevState
    }
}

export default reducer1

4、在入口文件index.js中引入provider,并包裹在App根组件外,其中的store就是创建的store对象

import React from 'react';
import ReactDOM from 'react-dom/client';

import { Provider } from "react-redux"

import App from './studyReactRedux/App';

import "./static/main.css"
import store from "./studyReactRedux/reactRedux/index";


const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <Provider store = { store }>
        <App></App>
    </Provider>
)

至此在react所有的组件中都有了store对象,方便存取全局状态了

接下来就是在组件中存值取值了

1、在组件中取值

  <div> {props.num} </div>
  const matStateToProps = (state) => {
        return {
             num: state.Reducer1.num
        }
   }
  export default connect(matStateToProps, mapDispatchToProps)(Home)

2、组件中存值(同步)

const handleClick = (val) => {
	props.changeVal(val)
}

<button onClick={ () => handleClick('同步传过去的值') }>同步存值</button>

const mapDispatchToProps = {
    changeVal(val) {
         return {
              type: 'TYPE1',
              value: val
          }
    }
}
export default connect(matStateToProps, mapDispatchToProps)(Home)

3、组件中存值(异步)

const handleClick = (val) => {
	props.changeVal(val)
}

<button onClick={ () => handleClick('同步传过去的值') }>同步存值</button>

const mapDispatchToProps = {
    changeVal(val) {
         return (dispatch) => {
              setTimeout(()=> {
					dispatch({
						type: 'TYPE1',
						value: val
					})
              }, 300)
         }
    }
}
export default connect(matStateToProps, mapDispatchToProps)(Home)

react-redux持久化

// 持久化可以自己在存状态的时候自己往local  session里面存值,借助redux-persist库
// 1、下载redux-persist
yarn add redux-persist

// 2、修改 store文件
 /**
 *
 *      react-redux的使用步骤
 *
 *          1、引入react-redux  和  redux  和  redux-thunk
 *
 *          2、index.js中引入 import { Provider } from "react-redux"
 *
 *          3、在根组件中App外面包上一层  <Provider store={ store }></Provider>, 其中store就是redux中创建的store对象
 *
 *          4、在组件中使用connect( (state)=>{
 *              return { state: state.xxxReducer.xxx }
 *          } )(App)
 *          其中的 connect 是从 react-redux 中解构出来的    import { connect } from "react-redux"
 *          connect函数中有两个参数: 第一个是从store状态中取值的,第二个是dispatch传值的
 *
 *          详细见home中的child1给child2传值, child2给child1传值
 */

import { createStore, combineReducers, applyMiddleware } from "redux"

import reduxThunk from "redux-thunk"


import {persistStore, persistReducer} from 'redux-persist'
import storage from 'redux-persist/lib/storage'

import Reducer1 from "./reducer/Reducer1"
import Reducer2 from "./reducer/Reducer2"
import Reducer3 from "./reducer/Reducer3"

const persistConfig = {
    key: 'item',
    storage,
    whitelist: ['Reducer1']  // 表示只持久化 Reducer1的值  blacklist: ['Reducer2'] 表示不持久化Reducer2
}

const reducer = combineReducers({
    Reducer1,
    Reducer2,
    Reducer3,
})

const myPersistReducer = persistReducer(persistConfig, reducer)

const store = createStore(myPersistReducer, applyMiddleware(reduxThunk))

const persistor = persistStore(store)

export { store, persistor }



// 3、修改入口文件 index.js
import React from 'react';
import ReactDOM from 'react-dom/client';

import { Provider } from "react-redux"

import App from './studyReactRedux/App';

import "./static/main.css"
import { store, persistor } from "./studyReactRedux/reactRedux/index";

import {PersistGate} from 'redux-persist/integration/react'

import { HashRouter } from "react-router-dom"


const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <Provider store = { store }>
        <PersistGate loading={null} persistor={persistor}>
        	<HashRouter>
            	<App></App>
           	</HashRouter>
        </PersistGate>
    </Provider>
)

不管是同步改状态还是异步改状态,只要dispatch就会发布action动作到store对象中,store交给reducer来处理修改响应的状态,从而达到了解耦的效果

redux的使用详解

redux是原生js实现的,和react没有直接的关系,使用起来相对react-redux稍微麻烦点,需要使用人员自己动手进行消息订阅和取消订阅

配置store对象和react-redux一样,见上面配置文件,只是不需要在App根组件中注入provider供应商
在使用的过程中不太一样,没有connect高阶组件

1、组件中取值

// 其中的store就是引入的store对象
const [val, setVal] = useState(store.getState().Reducer1.num)  // 取store中的初始值

useEffect(()=>{
	// 订阅消息,当store中的值发生改变的时候就会走到此方法里面来
	const unsubscibe = store.subscribe(() => {
		setVal(store.getState().Reducer1.num)
	})
	return() => {
		// 取消订阅
		unsubscibe()
	}
}, [])

<div>{val}</div>

2、组件中存值(同步)

handleClick(val) {
	store.dispatch({
		type: 'TYPE1',
		value: val
	})
}

3、组件中存值(异步)

	handleClick(val) {
		store.dispatch((dispatch) => {
			dispatch({
				type: 'TYPE1',
				value: val
			})
		})
	}

加载全部内容

相关教程
猜你喜欢
用户评论