一文搞懂redux在react中的初步用法
Redux是一個數(shù)據(jù)狀態(tài)管理插件,當使用React或是vue開發(fā)組件化的SPA程序時,組件之間共享信息是一個非常大的問題。例如,用戶登陸之后客戶端會存儲用戶信息(ID,頭像等),而系統(tǒng)的很多組件都會用到這些信息,當使用這些信息的時候,每次都重新獲取一遍,這樣會非常的麻煩,因此每個系統(tǒng)都需要一個管理多組件使用的公共信息的功能,這就是redux的作用。
如果你是從來沒有接觸過redux的開發(fā)者,希望您能夠有耐心的看一看,我也是看好很多博客慢慢自己總結(jié)的?。。?!比大佬們一個一個分布找要強一點。
import React, { Component, Fragment } from 'react';
//Class引入
import { connect } from 'react-redux';
//Hook引入
import { useSelector, useDispatch } from 'react-redux'
import { add, clear } from '../../redux/actions/count';
//hook 展示組件
const CountItem = (props) => {
// 解構(gòu)出來
const {
count,
flag,
add,
clear
} = props
return (
<>
<h2>當前求和為:{count}</h2>
<h3>當前Flag:{flag ? 'true' : 'false'}</h3>
<button onClick={add}>點擊+1</button>
<button onClick={clear}>清零</button>
</>
)
}
//hook 容器組件
const Count = () => {
const count = useSelector(state => state.sum)
const flag = useSelector(state => state.flag)
const dispatch = useDispatch()
const countAdd = () => {
console.log(add.type)
dispatch(add(1))
}
const clearNum = () => {
dispatch(clear())
}
return <CountItem count={count} flag={flag} add={countAdd} clear={clearNum} />
}
export default Count
// class 展示組件
// class Count extends Component {
// add = () => {
// // 通知redux
// this.props.add(1);
// };
// clear = () => {
// this.props.clear();
// };
// render() {
// return (
// <Fragment>
// <h2>當前求和為:{this.props.count}</h2>
// <h3>當前Flag:{this.props.flag ? 'true' : 'false'}</h3>
// <button onClick={this.add}>點擊+1</button>
// <button onClick={this.clear}>清零</button>
// </Fragment>
// );
// }
// }
// class 容器組件
// export default connect(
// // 1.狀態(tài)
// state => ({ count: state.sum, flag: state.flagState }),
// // 2.方法
// { add, clear }
// )(Count);
基本的使用差不多就是這個樣子,我們在hook上面用到的關(guān)鍵方法就是useSelector來使用redux的state、用dispatch來調(diào)用reduce;在class組件中用connect進行state和方法(reduce)的關(guān)聯(lián)。
這里面難點就在于reduce和state
這里的reduce是什么
上面的代碼里面我們用到了add和clear這兩個方法,我們新建一個js文件來實現(xiàn)這兩個方法。
// 為Count組件創(chuàng)建action對象
// 引入常量
import { ADD, CLEAR } from '../constant';
// 創(chuàng)建加一action對象的函數(shù)
export const add = data => ({
type: ADD,
data,
});
// 創(chuàng)建清零action對象的函數(shù)
export const clear = data => ({
type: CLEAR,
data,
});
上面有常量----這是為了方便actionType的統(tǒng)一管理,創(chuàng)建對應的action對象有助于代碼模塊化。
貼上,自己建一個constant.js放進去
export const ADD = 'add'; export const CLEAR = 'clear';
到這里我們的action對象定義的差不多了,我們要進行reducer的管理了。也就是dispatch分發(fā)上面的action對象來實現(xiàn)state的更新
在reducer文件夾里面我們定義一個count.js
// 為Count組件創(chuàng)建一個reducer
// reducer接收兩個參數(shù):之前狀態(tài)的preState,動作對象action
import { ADD, CLEAR } from '../constant.js';
// 設定初始狀態(tài)
const initState = 0;
export default function addReducer(preState = initState, action) {
// 從action中獲取type和data
const { type, data } = action;
// 根據(jù)type決定如何加工數(shù)據(jù)
switch (type) {
case ADD:
return preState + data;
case CLEAR:
return 0;
// 初始化動作
default:
return preState;
}
}
上面的方法要通過dispatch來進行type的分發(fā)調(diào)用(強調(diào)加一)
到這里使用就完成了 接下來看配置redux到react項目中
這里就不要倒敘了,因為這里倒敘不合理。
這里關(guān)鍵的幾個配置
store.js的配置和全局的store的使用
先看全局使用store
在你的根路由下面用Provider包裹App。
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
import store from './redux/store';
import { Provider } from 'react-redux';
ReactDOM.render(
// Provider包裹App,目的:讓App所有的后代容器組件都能接收到store
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
這里面有個redux/store.js 看代碼
// 整個文檔只有一個store對象,createStore接收兩個參數(shù),第一個是state樹,第二個是要處理的action
//applyMiddleware 匯總所有的中間件變成一個數(shù)組依次執(zhí)行,異步處理
import { createStore, applyMiddleware } from 'redux';
//中間件
import thunk from 'redux-thunk';
//匯總所有的reducer
import allReducers from './reducers/index';
//這里是goole的調(diào)試調(diào)試工具,具體使用:百度
import { composeWithDevTools } from 'redux-devtools-extension';
// 暴露store
export default createStore(allReducers, composeWithDevTools(applyMiddleware(thunk)));
到這里這篇文章就要結(jié)束了,里面的一些執(zhí)行流程和原理我還不是理解,接下來仍要多多鞏固,多多學習。
以上就是一文解決redux在react中的初步使用的詳細內(nèi)容,更多關(guān)于redux在react中使用的資料請關(guān)注腳本之家其它相關(guān)文章!

