React Native使用Redux總結


1>npm安裝redux:

"react-redux": "^5.0.5",
"redux": "^3.7.1",
"redux-thunk": "^2.2.0"

2>大致結構目錄如下:

3>ActionTypes.js:

在使用redux過程中,需要給每個動作添加一個actionTypes類型,可以說是標示;
// 接收數據
export const RECEIVE_BEAUTY_LIST = 'RECEIVE_BEAUTY_LIST';
export const BACKIMAGE_URL = 'BACKIMAGE_URL';

4>Store: 就是保存數據的地方,你可以把它看成一個容器。整個應用只能有一個 Store。

5>State:Store對象包含所有數據。如果想得到某個時點的數據,就要對 Store 生成快照。這種時點的數據集合,就叫做 State。

當前時刻的 State,可以通過store.getState()拿到。

/**
 * 創建Store,整合Provider
 * @flow
 */
import thunk from 'redux-thunk';
import { createStore, applyMiddleware, compose } from 'redux';
import rootReducer from './../Reducers/RootReducers';

let store = createStore(rootReducer, {}, compose(
  applyMiddleware(thunk),
  window.devToolsExtension ? window.devToolsExtension() : f => f
))

export default store;

6>Actions:

State 的變化,會導致 View 的變化。但是,用戶接觸不到 State,只能接觸到 View。所以,State 的變化必須是 View 導致的。Action 就是 View 發出的通知,表示 State 應該要發生變化了。

Action 是一個對象。其中的type屬性是必須的,表示 Action 的名稱。

import * as types from './../ActionTypes';

import {
    AsyncStorage,
} from 'react-native';

let KEY = 'PSMeiTuan';
export function backImage() {
    return dispatch => {
        return AsyncStorage.getItem(KEY,(Error,result)=>{
                if (result === null){
                    // 使用dispatch存儲值
                    dispatch(getBackImage('img'))
                } else {
                    console.log('獲取圖片成功' + result);
                    dispatch(getBackImage(result));
                }
            });
        }
};

export function getBackImage(imageURL) {
    return {
        type: types.BACKIMAGE_URL,
        imageURL  // 鍵值相等可以直接這么寫
    }
}

7>Reducers:

Store 收到 Action 以后,必須給出一個新的 State,這樣 View 才會發生變化。這種 State 的計算過程就叫做 Reducer。

Reducer 是一個函數,它接受 Action 和當前 State 作為參數,返回一個新的 State。

import * as types from './../ActionTypes';

const initialState = {
    loading: false,
    beauty: [],
    imageURL: 'https://ws1.sinaimg.cn/large/610dc034ly1fgllsthvu1j20u011in1p.jpg'
}

export default function beautyReducers(state = initialState, action) {
    switch (action.type) {
        case types.RECEIVE_BEAUTY_LIST:
            console.log('收到消息');
            return Object.assign({}, state, {
                loading: true,
                beauty: action.beauty
            });
        case types.BACKIMAGE_URL:
            return Object.assign({}, state, {
                imageURL:action.imageURL
            });
        default:
            return state;
    }
}

8>connect連接頁面和Reducer:<這里只記錄一個頁面選擇圖片,使用redux保存圖片,另一個頁面展示選擇的圖片>

BeautyPage.js選擇圖片頁面:

// 導入相關類
import { connect } from 'react-redux'; import {fetchBeautyGirlData} from './../../../Redux/Actions/BeautifulGirlAction'; import { backImage, getBackImage } from './../../../Redux/Actions/BackImageAction';;
// 連接reducer
export default connect((state) => {
    const { beautyReducers } = state;  // 這里的beautyReducers注意和對應的reducer文件export的類相同
    return {
        beautyReducers
    }
}, { backImage,getBackImage, fetchBeautyGirlData })(BeautyPage) // 這里是對應的存值的方法,BeautyPage是導出當前模塊
 // 點擊圖片,保存圖片
    onImageClick(item) {
        // alert(item.url);
        const {navigate,goBack,state} = this.props.navigation;
        // 方法一: 在第二個頁面,在goBack之前,將上個頁面的方法取到,並回傳參數,這樣回傳的參數會重走render方法
        // state.params.callback(item.url);
        let KEY = 'PSMeiTuan';
        AsyncStorage.setItem(KEY,item.url,(error)=>{
            if (error){
                console.log('存儲失敗' + error);
            } else {
                console.log('存儲成功');
                // 方法二: 這里可以發送通知到首頁
                // DeviceEventEmitter.emit('SHITUIMAGE',url);
                // 方法三:
                this.props.getBackImage(item.url);
        }
    });
    // 返回當前頁
        goBack();
    }

ReduxDemo.js對圖片進行顯示:

import { backImage,getBackImage } from './../../../Redux/Actions/BackImageAction';

連接reducer:

export default connect((state) => {
    const { beautyReducers } = state;
    return {
        beautyReducers
    };
},{ backImage,getBackImage })(ReduxDemo)
    /**
     * 此頁面調用順序:
     * 1>render;
     * 2>componentDidMount;
     * 3>componentWillReceiveProps;
     * 4>render;
     */
    // 使用
    componentDidMount(){
        console.log('componentDidMount');
        // 使用backImage方法。
        this.props.backImage();  
    }

    componentWillReceiveProps(nextProps){
        console.log('componentWillReceiveProps');
        // 最開始的值
        console.log(nextProps.beautyReducers);
        // 之前存儲的值
        console.log(this.props.beautyReducers);

        const { navigate } = this.props.navigation;
        const { imageURL } = nextProps.beautyReducers;

        if (this.props.beautyReducers.imageURL !== imageURL){
            if (imageURL) {
                imageUri = imageURL;
            }
        }
    }

暫時的理解就是Redux可以用來數據請求的時候以state存儲數據,某個頁面值改變進行值的存儲,以實現不同頁面都可以很輕松的取得數據.

暫時只實現和掌握了簡單的使用,高級用法后面學習積累!!!😄


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM