react-native, react-navigation, redux 学习笔记

前端之家收集整理的这篇文章主要介绍了react-native, react-navigation, redux 学习笔记前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

redux的使用

react-native,react,react-redux,react-navigaition,redux-thunk,redux-persist

用户发出action,reducer函数算出新的state,view重新渲染

三大原则

  1. 单一数据源,利用props的形式向下传播(react数据流决定)

  2. state只读,通过action修改

  3. 通过纯函数reducer来修改组件状态,reducer是描述action动作的纯函数

react-redux 连接react和redux

  1. import { connect,Provider } from 'react-redux'

connet([mapStateToProps],[mapDispatchToProps],[mergeProps])(App)

  • mapStateToProps: 基于全局的state,选择我们要注入的props

  • 不同的组件分开connec

  1. function select(state){
  2. return{
  3. // 把state.todos注入,读取方法: this.props.visibleTodo
  4. visibleTodo: state.todos
  5. }
  6. }
  7.  
  8. const todoApp connect(select)(App)
  9. // export default todoApp
  1. // store = "balabala"
  2. <Provider store={store}>
  3. <todoApp />
  4. </Provider>

redux三剑客

  1. // 先确定一下初始状态(状态表示的格式)
  2. export default {
  3. money: 0,lastJob:'no job'
  4. }

ACTION

  • 定义动作,比如抢劫银行、搬砖,但是怎么抢怎么搬还是reducer来定

  1. /**
  2. * Created by liuyiman on 2017/7/3.
  3. */
  4.  
  5. // 定义一个menoy+的action
  6. function addmoney(money){
  7. return {
  8. // 可以用一个文件管理type,之所以是type是因为我的reducer要根据这个来判断
  9. type: 'ADD_MONEY',money
  10. }
  11. }
  12. function setLastJob(job){
  13. return {
  14. type: 'SET_JOB',job
  15. }
  16. }
  17. // 定义一个赚钱的方式1 ,抢劫银行
  18. export function robBank(){
  19. return (dispatch,getState) => {
  20. // 赚一百万
  21. let { earn } = getState()
  22. dispatch(addmoney(earn.money + 1000000))
  23. return dispatch(setLastJob('robber'))
  24. }
  25. }
  26. // 定义一个赚钱的方式2,建材转移者
  27. export function moveBrick(){
  28. return (dispatch,getState) => {
  29. console.log('s',getState())
  30. let { earn } = getState()
  31. // 赚一块钱
  32. dispatch(addmoney( earn.money + 1 ))
  33. dispatch(setLastJob('brick mover'))
  34. }
  35. }
  36. // 破产,数据清零
  37. export function goBroke() {
  38. return {
  39. type: 'BROKE',money: 0,job:'broke'
  40. }
  41. }

reducers

  • 描述action如何改变store(in fact state)

  1. import { combineReducers } from 'redux'
  2. import initializeState from './initializeState'
  3. // 定义一个reducer
  4. function earn( state = initializeState,action ) {
  5. switch (action.type) {
  6. case 'ADD_MONEY':
  7. return{
  8. ...state,money:action.money
  9. }
  10. case 'SET_JOB':
  11. return{
  12. ...state,lastJob:action.job
  13. }
  14. case 'BROKE':
  15. return{
  16. ...state,money:action.money,lastJob:action.job
  17. }
  18. default:
  19. return state
  20. }
  21. }
  22.  
  23. export default earn

store

  • 不同的组件可以 connet 到不同的 store

  1. import { createStore,applyMiddleware,compose,combineReducers } from 'redux'
  2. import thunkMidlleware from 'redux-thunk'
  3. import earn from './reducers'
  4. import { persistStore,autoRehydrate} from 'redux-persist'
  5. import { AsyncStorage } from 'react-native'
  6.  
  7. // base reducer
  8. let baseReducers = {
  9. earn: earn
  10. }
  11. /*
  12. * 考虑到后面要将react-navigation的reducer加进来,使用redux-persist,所以写了这个helper
  13. * const store = configStore(reducers)()
  14. * */
  15. const configStore = function (reducers = {}) {
  16. const rootReducer = combineReducers({
  17. ...baseReducers,...reducers
  18. })
  19. return function (_options = {}) {
  20. const store = createStore(
  21. rootReducer,_options.initialState,compose(
  22. applyMiddleware(thunkMidlleware),autoRehydrate()
  23. )
  24. )
  25. const options = {
  26. storage: AsyncStorage,blacklist: _options.blacklist
  27. }
  28. persistStore(store,options)
  29. return store
  30. }
  31. }
  32.  
  33. export default configStore

more

中间件 middleware

  • 对store.dispatch的重新定义

  • 在发出action和执行reducer之间,添加了其他功能

redux-thunk

使dispatch可以接受函数说作为参数,使异步的action可以被触发

  1. // 无论killSomeOne是Action create还是普通的返回{}的action
  2. this.props.dispath(killSomeOne('vincent'))

redux-persist

本地保存store状态(react-native 本地缓存),可以设置白名单黑名单自动保存等等,特别好用

  1. /*
  2. * 考虑到后面要将react-navigation的reducer加进来,使用redux-persist,options)
  3. return store
  4. }
  5. }
  6.  
  7. export default configStore

react-navigation + redux

  1. import React,{ Component } from 'react';
  2. import {
  3. AppRegistry,StyleSheet,Text,View,Button
  4. } from 'react-native';
  5. // navigation
  6. import { TabNavigator,addNavigationHelpers,StackNavigator } from 'react-navigation'
  7. // for connect redux and react
  8. import { Provider,connect } from 'react-redux'
  9. import configStore from './redux/store'
  10. // import actions
  11. import {moveBrick,robBank,goBroke} from './redux/actions'
  12. // initialState
  13. import initialState from './redux/store'
  14.  
  15. // 赚钱页面
  16. class Earn extends Component {
  17. constructor(props) {
  18. super(props)
  19. }
  20. render(){
  21. const { earn,dispatch } = this.props
  22. console.log( 'saa',initialState,earn )
  23. return(
  24. <View style={styles.container}>
  25. <Text>先赚一个亿!</Text>
  26. <Text>my money$:{earn.money}</Text>
  27. <Text>my last job:{earn.lastJob}</Text>
  28. <Button title="rob a bank" onPress={() => dispatch(robBank())}/>
  29. <Button title="move some Brick" onPress={() => dispatch(moveBrick())}/>
  30. <Text>价格指导:搬砖 -> $1; 打劫 -> $1000000</Text>
  31. <Button title="broke" onPress={() => dispatch(goBroke())}/>
  32. </View>
  33. )
  34. }
  35. }
  36.  
  37. // 传入 earn页面的redux
  38. const earnSelect = function (state) {
  39. return{
  40. earn: state.earn
  41. }
  42. }
  43. // 连接,吧earn上面的select传入earn的props里面
  44. const ConnnetedEarn = connect(earnSelect)(Earn)
  45.  
  46. // tab navigation的另一个页面
  47. class Screen extends Component{
  48. constructor(props){
  49. super(props)
  50. }
  51. render() {
  52. const { navigate } = this.props.navigation
  53. return(
  54. <View style={styles.container}>
  55. <Text>SCREEN!</Text>
  56. <Button title="to stack2" onPress={() => {navigate('Stack2')}}/>
  57. </View>
  58. )
  59. }
  60. }
  61.  
  62. // 注册一个tag navigator
  63. const AppNav = TabNavigator({
  64. 'earn':{
  65. screen: ConnnetedEarn
  66. },'screen': {
  67. screen: Screen
  68. }
  69. })
  70.  
  71. // stack navigation 的页面
  72. class Stack2 extends Component {
  73. constructor(props){
  74. super(props)
  75. }
  76. render(){
  77. const {navigate} = this.props.navigation
  78. return (
  79. <View style={styles.container}>
  80. <Text>Stack2</Text>
  81. <Button title="TO APP NAV" onPress={() => navigate('screen')}/>
  82. </View>
  83. )
  84. }
  85. }
  86.  
  87. /*
  88. * 注册stack
  89. * 一个是 上面的 tag navigation的页面
  90. * 另一个是 上面的 stack2
  91. * */
  92. const StackNav = StackNavigator({
  93. App:{
  94. screen: AppNav,title: 'app'
  95. },Stack2: {
  96. screen: Stack2,title: 'stack2'
  97. }
  98. })
  99.  
  100. const navInitialState = StackNav.router.getStateForAction(AppNav.router.getActionForPathAndParams('screen'))
  101. const navReducer = (state = navInitialState,action) => {
  102. console.log('state:',state)
  103. let nextState = StackNav.router.getStateForAction(action,state);
  104. console.log('action',action)
  105. return nextState || state
  106. }
  107.  
  108. /*
  109. * 加入navReducer,生成store
  110. * */
  111. const store = configStore({
  112. nav: navReducer
  113. })({
  114. blacklist:['nav']
  115. })
  116.  
  117. /*
  118. * stack app
  119. * 利用addNavigationHelper吧navigation传进去
  120. * */
  121. class App extends Component{
  122. render(){
  123. return(
  124. <StackNav navigation={addNavigationHelpers({
  125. dispatch: this.props.dispatch,state: this.props.nav
  126. })} />
  127. )
  128. }
  129. }
  130.  
  131. /*
  132. * 把nav传进去
  133. * */
  134. function select(state) {
  135. console.log('state',state)
  136. return {
  137. nav: state.nav
  138. }
  139. }
  140. /*
  141. * connect connect!
  142. * */
  143. const ConnectedApp = connect(select)(App)
  144.  
  145.  
  146. // 加上 provider和store
  147. class reduxLearn extends Component {
  148. render() {
  149. return (
  150. <Provider store={store}>
  151. <ConnectedApp/>
  152. </Provider>
  153. );
  154. }
  155. }
  156.  
  157. const styles = StyleSheet.create({
  158. container: {
  159. flex: 1,justifyContent: 'center',alignItems: 'center',backgroundColor: '#F5FCFF',},welcome: {
  160. fontSize: 20,textAlign: 'center',margin: 10,instructions: {
  161. textAlign: 'center',color: '#333333',marginBottom: 5,});
  162.  
  163. // 注册
  164. AppRegistry.registerComponent('reduxLearn',() => reduxLearn);

猜你在找的React相关文章