1. 程式人生 > >react-native 從簡單的事件分發來介紹redux

react-native 從簡單的事件分發來介紹redux

演示效果:

理論知識:

理論知識重複炒冷飯等於製造網路垃圾,所以貼上幾篇我覺得寫得不錯的給大家瞅瞅

核心理念:

Store:應用只有一個單一的 Store,State是這個狀態集合某一時刻的狀態
Action:改變state的載體,也是Store的資料來源
Reducer:更新Store的具體操作者

ok,你現在肯定雲裡霧裡的,我們用程式碼邊寫邊解釋

專案結構:

Action相關

MathType

export const ADD_TYPE = 'ADD_TYPE';
export const MINUS_TYPE = 'MINUS_TYPE'
;

這裡是2個常量,”加型別”,”減型別”,我們每種action都有他相對應的型別,可以寫在Action裡也可以寫一個型別對他進行劃分,我習慣是拆的越細越好

MathAction

// action型別
import * as types from '../type/MathType';

// 每一個action方法返回一個新的"state"物件,他就是應用當前的狀態
export function add(intvalue) {
    console.log('---> MainAction add intvalue ' + intvalue);
    return {
        type
: types.ADD_TYPE, result: intvalue, } }; export function minus(intvalue) { console.log('---> MainAction minus intvalue ' + intvalue); return { type: types.MINUS_TYPE, result: intvalue, } };

Reducer相關

MathReducer

import  * as Type from'../type/MathType'
; //初始化 const initState = { result: 0 }; export default function mathReducer(state = initState, action = {}) { switch (action.type) { case Type.ADD_TYPE: console.log('---> mathReducer action.type ' + action.type); return { ...state, result: action.result + 10, }; break; case Type.MINUS_TYPE: console.log('---> mathReducer action.type ' + action.type); return { ...state, result: action.result - 10, }; default: return state; } }

肉眼看起來很簡單,這裡接受兩種型別的action一個是➕,一個是➖,每次他都會改變傳入引數的值,而且是一定改變,一定會+10或者-10!
reducer只是一個方法,傳入什麼,返回什麼。結果是個恆定值,只要傳入引數不變,返回引數一定也不變!

reducers

import  Mathreducer from './Mathreducer';

import  {combineReducers} from 'redux';

export default combineReducers({
    mathStore: Mathreducer,
});

這是一個reducer的大容器,你所有reducer丟一個方法裡也不是不能處理,但是效能差加難以維護,所以redux提供combineReducers來幫你整合reducer

Store相關

store是個應用級持有的物件,所以我們把他放到了”根”頁面裡去做初始化,因為我們之後還會用到非同步action,所以還用到redux-thunk的相關內容

import {Provider} from 'react-redux';
import {createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import reducers from'./reducer/reducers';
const middlewares = [thunk];
const createSoreWithMiddleware = applyMiddleware(...middlewares)(createStore);
import  React from 'react';
import  Main from'./Main';

export default class App extends React.PureComponent {
    constructor(props) {
        super(props);

        this.state = {
            store: createSoreWithMiddleware(reducers)
        }
    }

    //前面一些只是物件,方法相關的操作,肉眼可以識別,Provider是讓我們決定使用redux的一個原因,它可以讓我們操作容器內的元件卻不需要手動傳遞內容
    //想想複雜應用來一個 4層以上的json要你你自己操作的話的工作量吧
    render() {
        return (
            <Provider store={this.state.store}>
                <Main/>
            </Provider>
        )
    }
}

只需要在外面套一層,所有子控制元件的屬性竟在掌握!

頁面程式碼

import React from'react';


import {connect} from 'react-redux';
//加減的兩種action
import {add, minus} from './action/MathAction';

import {
    Text,
    View,
    TouchableHighlight,
} from 'react-native';

class Main extends React.Component {
    constructor(props) {
        super(props);
        this.addPress = this.addPress.bind(this);
        this.minusPress = this.minusPress.bind(this);
        //初始值,也可以是外部傳入
        this.state = {
            intvalue: 100,
        }
    }

    addPress() {
        console.log('---> Main addPress');
        this.props.dispatch(add(this.state.intvalue));
    }

    minusPress() {
        console.log('---> Main minuPress');
        //dispatch(action) 方法更新 state
        this.props.dispatch(minus(this.state.intvalue));
    }

    //狀態變化時會被呼叫
    shouldComponentUpdate(nextProps, nextState) {
        console.log('---> Main shouldComponentUpdate');
        if (nextProps.result !== this.props.result) {
            this.state.intvalue = nextProps.result;
            console.log('---> Main shouldComponentUpdate this.state.intvalue ' + this.state.intvalue);
            return true;
        }
    }

    render() {
        console.log('---> Main render');
        return (
            <View style={{justifyContent: 'center'}}>
                <TouchableHighlight onPress={this.addPress}>
                    <Text style={{fontSize: 15}}>
                        按我會加
                    </Text>
                </TouchableHighlight>
                <TouchableHighlight style={{marginTop: 30}} onPress={this.minusPress}>
                    <Text style={{fontSize: 15}}>
                        按我會減
                    </Text>
                </TouchableHighlight>
                <Text style={{marginTop: 30, color: '#ffaa11'}}>{this.state.intvalue}</Text>
            </View>
        )
    }
}

function select(store) {
    return {
        result: store.mathStore.result,
    }
}
//connect方法建立資料與狀態的關係,達到重新整理ui的效果
export  default  connect(select)(Main);

這樣這個簡單的demo就講完了,什麼?看不懂,我也覺得 這說的是啥啊,過程都沒講清楚,ok 看下console你就明白了!

//首頁被加載出來
05-19 20:52:49.094 5992-24741/? I/ReactNativeJS: ---> Main render

//頁面點選了 “按我會加”
05-19 20:52:57.746 5992-24741/? I/ReactNativeJS: ---> Main addPress

//action得到了響應獲取到了 100(正常的方法呼叫嘛?繼續看!)
05-19 20:52:57.747 5992-24741/? I/ReactNativeJS: ---> MainAction add intvalue 100

//傳遞到了reducer獲取到了觸發的型別
05-19 20:52:57.747 5992-24741/? I/ReactNativeJS: ---> mathReducer action.type ADD_TYPE

//頁面收到了state改變的訊息,回撥被觸發
05-19 20:52:57.759 5992-24741/? I/ReactNativeJS: ---> Main shouldComponentUpdate

//新的值是之前的100+reducer的10=110
05-19 20:52:57.759 5992-24741/? I/ReactNativeJS: ---> Main shouldComponentUpdate this.state.intvalue 110

//重新整理資料
05-19 20:52:57.759 5992-24741/? I/ReactNativeJS: ---> Main render

//第二次操作,不解釋了
05-19 20:53:02.010 5992-24741/? I/ReactNativeJS: ---> Main minuPress
05-19 20:53:02.010 5992-24741/? I/ReactNativeJS: ---> MainAction minus intvalue 110
05-19 20:53:02.010 5992-24741/? I/ReactNativeJS: ---> mathReducer action.type MINUS_TYPE
05-19 20:53:02.015 5992-24741/? I/ReactNativeJS: ---> Main shouldComponentUpdate
05-19 20:53:02.015 5992-24741/? I/ReactNativeJS: ---> Main shouldComponentUpdate this.state.intvalue 100
05-19 20:53:02.015 5992-24741/? I/ReactNativeJS: ---> Main render

action reducer本身看起來平淡無奇,但是在store內輪轉使得我們省去了大量setState的人工操作,避免了各種不可描述的render().

但是 redux處理不好會各種多次render頁面,之後的文章我會講一講非同步的action和react-native優化

我是王亟亟!我們下篇見

有問題可以掃碼加好友詢問噢,非公眾號,閒人勿擾!
這裡寫圖片描述

相關推薦

react-native 簡單事件分發介紹redux

演示效果: 理論知識: 理論知識重複炒冷飯等於製造網路垃圾,所以貼上幾篇我覺得寫得不錯的給大家瞅瞅 核心理念: Store:應用只有一個單一的 Store,State是這個狀態集合某一時刻的狀態 Action:改

React Native零開始(六)ListView的簡單使用

/** * Created by 11158 on 2017-01-16. */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, List

react native 0.5項目目錄介紹

lock 文本文 通用組 gas app.js Redux editor commons ant ├── src // Ract Native │ ├── app // redux部

React Native 入門到插件化嘗試

插件化 圖片 入門到 嘗試 技術 ima native clas image React Native 從入門到插件化嘗試

react-native點擊事件

點擊 this his ati res native 事件 reac react 點擊事件 <View> <Button title="點擊事件" onPress={this._onPressButton.bind(this)}/></

React Native入門到放棄

React Native中文社群: https://reactnative.cn/docs/getting-started React Native中文社群論壇: http://bbs.reactnative.cn/category/4/求助專區 React Native 豆瓣demo:

react native Animated簡單使用方法

import { Animated, } from 'react-native'; constructor(props){ super(props) this.state={ fadeInOpacity: new Animate

《移動Web前端高效開發實戰HTML 5 + CSS 3 + JavaScript Webpack + React Native + Vue.js + Node.js 》介紹推薦

移動網際網路的興起和快速普及,給前端開發人員帶來了新機遇。移動Web前端技術作為整個技術鏈條中重要的一環,卻亂象叢生。本書是一本梳理移動前端和Native客戶端技術體系的入門實戰書。 本書涵蓋了移動Web前端開發中的各個關鍵技術環節,共14章。分別從HTML 5、C

React Native急診到重症監護》-- React Native for mac 環境配置

這段時間移動前端開發有兩個技術很火,一個就是HTML5,一個就是React Native,這兩個非要說誰好誰差,這個我認識淺薄不太好說,剛剛接觸,還在學習的過程中。好與壞很多大神已經發表了自己的意見,對於這個不再贅述。 搭建Mac的環境比較簡單,想要更深入的瞭解,可以登陸官網去檢視相關

混合開發的大趨勢之一React Native簡單的登入介面

這些天都在學習RN這部分吧,然後寫了個簡單的登陸業務,從“實戰”中講解吧 先上下效果圖 效果很簡單就是2個<Text/> 2個<TextInput/>1個<Button/> 按鈕控制元件是第三方的,就是為了演示下如何在

react-native熱更新之CodePush詳細介紹及使用方法

react-native熱更新之CodePush詳細介紹及使用方法 2018年03月04日 17:03:21 clf_programing 閱讀數:7979 標籤: react native熱更新code pus

一起學react native實現簡單購物車

前言 實現比較簡單的購物車例項http://www.jianshu.com/p/c581c48a601f 這裡寫圖片描述 程式碼 程式碼結構 這裡寫圖片描述 紅色部分儲存了listitem的資料跟檢視 黃色部分是對於其的引用 主體實現部分 這裡

React-Native零到有(1)——基礎環境搭建

開發平臺:windows 10 x64 目標平臺:Java Android 軟體及環境: 1. Java Development Kit 1.8.x(更高版本暫不提供支援) 2. Python

React-Native入門到放棄(二)

demo完成之後,公司沒用,沒有精力再弄了,給大家列出學習資料 React Native ES6 系列教程 開源APP 研究原始碼也是一個很好的學習方式

AsyncStorage 和 react-native-storage 簡單封裝

AsyncStorage是一個簡單的、非同步的、持久化的Key-Value儲存系統,它對於App來說是全域性性的,具體詳細api可檢視連結,點選檢視詳細內容,本文主要是基於AsyncStorage 和 github(react-native-storage),做了一層簡單的封

React Native 零到一個小專案

前陣子開始學習 React Native,一個人摸滾帶爬的也算是能寫個 小專案 了,在這裡分享一下自己從零開始學習的過程,也推薦一些比較優秀的學習資源,讓大家學習過程可以提高一些效率。 在路上 一、環境搭建和 IDE 選型 React Native 環境搭建可以看 

react native點選事件傳遞引數

比如我們定義一個TouchableOpacity點選事件,該方法需要接收一個引數值,如下 _gotoSubClass(sectionID, rowID) { console.log("sect

React Native跨平臺移動應用開發框架介紹

好久沒有來更新部落格了,給大家說聲抱歉,人一旦懶惰起來連自己都害怕。可能是因為一個人生活,少了很多動力吧。這都是在給自己找理由。我在不偷懶了。 最近我要入坑了,公司安排我要開始搞React

react-native入門到放棄

剛剛度過了繁忙的一個月,連續不斷的需求讓自己有點招架不住了。寫的程式碼質量有些堪憂,又導致不斷的修改bug,陷入了惡性迴圈中了,不過隨著最近最後一個需求即將完結,終於抽空寫寫rn相關的內容了。這個標題略有寫浮誇,主要是為了吸引眼球,也有自己感受的原因。 一

react-native簡單使用

一、網上搜集RNandroid的問題 版本更新太快,到現在還沒有到達版本1.0,技術並沒有那麼穩定 使用了RN,就意味著和Google的android開發控制元件走上了兩條不一樣的路線。 二、目前存在的問題 1、react-native庫會直接帶動