1. 程式人生 > 程式設計 >一文搞懂redux在react中的初步用法

一文搞懂redux在react中的初步用法

Redux是一個數據狀態管理外掛,當使用React或是vue開發元件化的SPA程式時,元件之間共享資訊是一個非常大的問題。例如,使用者登陸之後客戶端會儲存使用者資訊(ID,頭像等),而系統的很多元件都會用到這些資訊,當使用這些資訊的時候,每次都重新獲取一遍,這樣會非常的麻煩,因此每個系統都需要一個管理多元件使用的公共資訊的功能,這就是redux的作用。

如果你是從來沒有接觸過redux的開發http://www.cppcns.com者,希望您能夠有耐心的看一看,我也是看好很多部落格慢慢自己總結的!!!!比大佬們一個一個分佈找要強一點。

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) => {
    // 解構出來
    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&JfOJMUgt; // </Fragment> // ); // } // } // class 容器元件 // export default connect( // // 1.狀態 // state => ({ count: state.sum,flag: state.flagState }),// // 2.方法 // { add,clear } // )(Count);

基本的使用差不多就是這個樣子,我們在hook上面用到的關鍵方法就是useSeJfOJMUlector來使用redux的state、用dispatch來呼叫reduce;在class元件中用connect進行state和方法(reduce)的關聯。

這裡面難點就在於reduce和state

這裡的reduce是什麼

上面的程式碼裡面我們用到了add和clear這兩個方法,我們新建一個js檔案來實現這兩個方法。

// 為Count元件建立action物件
// 引入常量
import { ADD,CLEAR } from '../constant';

// 建立加一action物件的函式
export const add = data => ({
    type: ADD,data,});

// 建立清零action物件的函式
export const clear = data => ({
    type: CLEAR,});

上面有常量----這是為了方便actionType的統一管理,建立對應的action物件有助於程式碼模組化。
貼上,自己建一個constant.js放進去

export const ADD = 'add';
export const CLEAR = 'clear';

到這裡我們的action物件定義的差不多了,我們要進行reducer的管理了。也就是dispatch分發上面的action物件來實現state的更新

在reducer資料夾裡面我們定義一個count.js

// 為Count元件建立一個reducer
// reducer接收兩個引數:之前狀態的preState,動作物件action

import { ADD,CLEAR } from '../constant.js';

// 設定初始狀態
const initState = 0;

export default function addReducer(preState = initState,action) {
    // 從action中獲取type和data
    const { type,data } = action;
    // 根據type決定如何加工資料
    switch (type) {
        case ADD:
            return preState + data;
        case CLEAR:
            return 0;
        // 初始化動作
        default:
            return preState;
    }
}

上面的方法要通過dispatch來進行type的分發呼叫(強調加一)

到這裡使用就完成了 接下來看配置redux到react專案中

這裡就不要倒敘了,因為這裡倒敘不合理。
這裡關鍵的幾個配置
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接收兩個引數,第一個是state樹,第二個是要處理的action
//applyMiddleware 彙總所有的中介軟體變成一個數組依次執行,非同步處理
import { createStore,applyMiddleware } from 'redux';
//中介軟體
import thunk from 'redux-thunk';
//彙總所有的reducer
import allReducers from './reducers/index';
//這裡是goole的除錯除錯工具,具體使用:百度
import { composeWithDevTools } from 'redux-devtools-extension';

// 暴露store
export default createStore(allReducers,composeWithDevTools(applyMiddleware(thunk)));

到這裡這篇文章就要結束了,裡面的一些執行流程和原理我還不是理解,接下來仍要多多鞏固,多多學習。

以上就是一文解決redux在react中的初步使用的詳細內容,更多關於redux在react中使用的資料請關注我程式設計客棧們其它相關文章!