React-Native項目中使用Redux

前言

網上別人的文檔都是 直接 就是上redux redux-thunk react-redux ,immutable這樣的一套,這個有經驗的看還行,新手看就很吃力了,須要瞭解一步一步的安裝redux達到開發要求react

我以爲這須要一個學習的過程,適得其反不是好事git

這是我寫項目的逐步搭建的過程,歡迎查看源代碼github-pinduoduogithub

Redux

  1. 安裝redux(後面再安裝(react-redux)

由於redux是js的部分 因此不須要linknpm

npm install redux--save

安裝完成後確承認以正常啓動json

  1. 建立store

個人項目結構redux

和React項目同樣的項目結構react-native

index.jsbash

import { createStore } from 'redux'
import reducer from './reducer'

export default createStore(reducer) // 導入state

reducer.jsapp

import actionTypes from './actionTypes'
const defaultState = { // 初始化state
  data: 'my is redux!!!!' 
}

export default (state = defaultState, action) => {
  console.log(action)
  if (action.type == actionTypes.CHANGE) { // 修改state
    const newState = JSON.parse(JSON.stringify(state))
    newState.data = 'change data!!!'
    return newState
  }
  return state
}

actionTypes.jside

export default {
  CHANGE: 'change' // 定義統一的type
}

actionCreators.js

import actionTypes from './actionTypes'
export function change() { // 統一管理action
  return {
    type:  actionTypes.CHANGE
  }
}

最後在頁面裏面

import React, { Component } from 'react'
import {
  Text,
  StyleSheet,
  View,
  StatusBar,
  Dimensions,
  Button
} from 'react-native'
import store from '../../../store/index' // 導入store
import { change } from '../../../store/actionCreators'  // 導入action
export default class Popular extends Component {
  constructor(props) {
    super(props)
    this.state = store.getState() // 初始化state,獲取redux裏面數據
    store.subscribe(() => { // 訂閱state的改變
      this.setState(store.getState())
    }) 
  }
  render() {
    return (
      <View>
        <Text>{this.state.data}</Text>
        <Button
          title="更新state"
          onPress={() => {
            store.dispatch(change())
          }}
        />
        <Button
          title="查看state"
          onPress={() => {
            console.log(store.getState())
          }}
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({})

最基礎的redux就使用成功了,可是這個還達不到咱們的開發要求,下面將引入react-redux

Redux + React-redux

若是不瞭解React-redux,請學習後再說,否則確定看不懂,React-redux文檔

React-redux文檔

以前咱們在組件裏面使用Redux直接去獲取數據,加入每一個頁面都這樣寫,會很麻煩,因此咱們要藉助react-redux來幫咱們處理store

修改以前寫的頁面代碼,去掉以前頁面使用state的地方

import React, { Component } from 'react'
import {
  Text,
  StyleSheet,
  View,
  StatusBar,
  Dimensions,
  Button
} from 'react-native'
import { change } from '../../../store/actionCreators'
class Popular extends Component {
  render() {
    return (
      <View>
        <Text>{this.props.data}</Text>
        <Button title="更新state" onPress={() => {
            //..
          }} />
        <Button
          title="獲取state"
          onPress={() => {
            //..
          }}
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({})

export default Popular

修改程序的掛載入口

index.js

/** @format */
import React, { Component } from 'react'
import { Provider } from 'react-redux'
import { AppRegistry } from 'react-native'
import store from './app/store'
import App from './app/routes/App'
import { name } from './app.json'

class Apps extends Component {
  render() {
    return (
       // 掛載store,讓app內部全部組件均可以使用
      <Provider store={store}>
        <App />
      </Provider>
    )
  }
}

AppRegistry.registerComponent(name, () => Apps)

這裏咱們就能夠在組件裏面經過connent來接收了

import React, { Component } from 'react'
import { connect } from 'react-redux'
import {
  Text,
  StyleSheet,
  View,
  StatusBar,
  Button
} from 'react-native'
import { change } from '../../../store/actionCreators'
class Popular extends Component {
  render() {
    return (
      <View>
        <StatusBar
          translucent={true} // 設置沉浸式狀態欄 正常狀況下 狀態欄高度爲20 這裏的20 須要頁面元素距離最上面 paddingTop:20
          backgroundColor={'rgba(0,0,0,0.1)'} // 設置狀態欄顏色
          animated={true} // 容許動畫切換效果
        />
        <Text>{this.props.data}</Text>
        <Button title="更新state" onPress={this.props.changeData} />
        <Button
          title="獲取state"
          onPress={() => {
            console.log(this.props.data)
          }}
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({})

const mapState = state => ({
  data: state.data
})

const mapDispatch = dispatch => ({
  changeData() {
    dispatch(change())
  }
})

export default connect(
  mapState,
  mapDispatch
)(Popular)

這裏咱們React-redux再次獲取並修改了redux裏面的數據,相對之下,使用React-redux後,頁面邏輯更加清楚

Redux + React-redux+immutable

immutable在平常開發裏面很常見,讓咱們的數據更加嚴謹

很簡單,首先安裝

npm install immutable

處理咱們store的數據

import actionTypes from './actionTypes'
import {fromJS} from 'immutable' 
const defaultState = fromJS({ // 將對象轉成immutable對象
  data: 'my is redux!!!!'
})

export default (state = defaultState, action) => {
  if (action.type == actionTypes.CHANGE) {
    return state.set('data','change Redux!!!')
  }
  return state
}

而後處理咱們頁面裏面引用數據的地方

const mapState = state => ({
  data: state.get('data') // immutable對象使用get獲取
})

redux的分離

將大量的store數據放在一塊兒是很是很差的行爲,咱們要將每一個組件之間的store儘量的分離

這裏用的是redux給咱們提供的 combineReducers 將store進行合併

修改頁面目錄結構,在頁面目錄裏面建立store

組件內部的sore代碼

Popular/store/reducer

import actionTypes from './actionTypes'
import {fromJS} from 'immutable'
const defaultState = fromJS({
  data: 'my is redux!!!!'
})

export default (state = defaultState, action) => {
  if (action.type == actionTypes.CHANGE) {
    return state.set('data','change Redux!!!')
  }
  return state
}

Popular/store/actionTypes

export default {
  CHANGE: 'change'
}

Popular/store/actionCreators

import actionTypes from './actionTypes'
export function change() {
  return {
    type:  actionTypes.CHANGE
  }
}

Popular/store/index

import reducer from './reducer'
import actionCreators from './actionCreators'
import actionTypes from './actionTypes'

export { reducer, actionCreators, actionTypes }
// 使用入口

這樣咱們就在組件內部新建了一個store,接下來咱們要把組件內部的store合併store裏面

./store/reducer

import { combineReducers } from 'redux'
import { reducer as homePopular } from '../src/home/Popular/store/index'

export default combineReducers ({
  homePopular: homePopular
})

這就完成了store的合併,這裏store變了,天然訪問就變了

Popular.js

const mapState = state => ({
  data: state.homePopular.get('data')
})

最後引入redux中間件

我通常狀況下使用redux-thunk

npm install redux-thunk
import { createStore,applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import reducer from './reducer'


export default createStore(
  reducer,
  applyMiddleware(thunk)
)

這裏不作樣式了,會的人天然會,不會的學習一下,學會使用很簡單

相關文章
相關標籤/搜索