React Native Redux学习
1.action
进行一定的逻辑,并将处理后的结果,使用dispatch以type的形势传递出去,结果在reduce里面处理结果2.reducers接受Action里面传出的type,根据type的类型更改state的值并将值返回给3.store进行配置store,在程序的入口中调用,调用后reduce更新的state就会传送到store中store会更具传回的state改变页面显示使用:在需要使用的页面中使用react-redux中的connect与store进行连接,/**
*在select中设置需要的state**/function select(store){ return {isLoggedIn: store.userStore.isLoggedIn, user: store.userStore.user,
}
}//页面与store链接export default connect(select)(Main);使用步骤:
1.在项目中导入包1>.导入react-redux2>导入redux3>导入redux-thunk4>导入redux-persist2.创建文件目录redux中使用的:1>.actions2>.store3>.reducers3.创建相关文件
1>.在store目录下创建index.js
import { applyMiddleware, createStore } from 'redux';import thunk from 'redux-thunk';import { persistStore, autoRehydrate } from 'redux-persist';import { AsyncStorage } from 'react-native';import reducers from '../reducers';const logger = store => next => action => { if(typeof action === 'function') console.log('dispatching a function'); else console.log('dispatching', action); let result = next(action); console.log('next state', store.getState()); return result;}let middlewares = [ logger, thunk];let createAppStore = applyMiddleware(...middlewares)(createStore);export default function configureStore(onComplete: ()=>void){ const store = autoRehydrate()(createAppStore)(reducers); let opt = { storage: AsyncStorage, transform: [], //whitelist: ['userStore'], }; persistStore(store, opt, onComplete); return store;}
2.创建入口文件,入口文件中使用react-redux中的Provider,在Provider中使用store
import React, { Component } from 'react';
//导入providerimport { Provider } from 'react-redux';//导入store中的configureStoreimport configureStore from './store/index';let store = configureStore();
import Root from './root';
export default class App extends Component{
constructor(){super(); this.state = { isLoading: true, store: configureStore(()=>{this.setState({isLoading: false})}) }
}
render(){if(this.state.isLoading){ console.log('loading app'); return null; }
/**
**使用store***/return ()
}
}3.创建Action
创建action文件import * as TYPES from './types';
// fake user data
let testUser = { 'name': 'juju', 'age': '24', 'avatar': ''};// for skip user
let skipUser = { 'name': 'guest', 'age': 20, 'avatar': '',};// login
export function logIn(opt){ return (dispatch) => {dispatch({'type': TYPES.LOGGED_DOING}); let inner_get = fetch('http://www.baidu.com') .then((res)=>{ dispatch({'type': TYPES.LOGGED_IN, user: testUser}); }).catch((e)=>{ AlertIOS.alert(e.message); dispatch({'type': TYPES.LOGGED_ERROR, error: e}); });
}
}// skip login
export function skipLogin(){ return {'type': TYPES.LOGGED_IN, 'user': skipUser,
}
}// logout
export function logOut(){ return {'type': TYPES.LOGGED_OUT
}
}4.在页面js中调用action
//将action导入页面,就可以从页面文件中使用action中的方法
import { logIn, skipLogin } from '../actions/user';reduce运行路线
配置store-->入口使用store页面中调用action->action将type发出去间接调用reduce->页面中使用connect将页面的state和store