react-native + redux 实践
来源:互联网 发布:数据库foreign key 编辑:程序博客网 时间:2024/05/07 18:56
一、rn环境搭建
看我的另外一篇文章 http://blog.csdn.net/bluefish89/article/details/77802507
二、rn起步
对于RN的时候,通过https://reactnative.cn/docs/0.50/getting-started.html 可知道,通过react-native引入组件,可在Component中的render方法使用JSX标签如Text、View、FlatList,通过react-native run-ios
构建,可在iPhone中运行出对应原生控件。
先看以下代码:
import React, { Component } from 'react';import { AppRegistry, StyleSheet, Text, View, TouchableHighlight} from 'react-native';export default class ReduxTest extends Component { constructor(props) { super(props); this.state = { keyword :'刘德华' }; } searchMusic(keyword) { this.setState({keyword:keyword} } render() { return ( <View style={styles.container}> <Text>{this.state.keyword}</Text> <TouchableHighlight underlayColor='#f1c40f' onPress={()=> this.updateData('更改了state')}> <Text>点我</Text> </TouchableHighlight> </View> ); }}AppRegistry.registerComponent('ReduxTest', () => ReduxTest);
点击按钮后,文本内容变成’更改了state’,这是因为调用了this.setState,通过该方法更新state,会触发render()重新更新UI。这就差不多是Rn的使用方法了,state用于保存数据,通过setState触发UI重绘,典型的状态机机制。
三、使用redux
redux中有三个基本概念,Action,Reducer,Store。
1.Action
Actions 是把数据从应用传到 store 的有效载荷。它是 store 数据的唯一来源。用法是通过 store.dispatch() 把 action 传到 store。
Action 有两个作用:
- 用Action来分辨具体的执行动作。比如是create 还是delete?或者是update?
操作数据首先得有数据。比如添加数据得有数据,删除数据得有ID。。action就是存这些数据的地方。
简单说,就是用来标识想要进行什么操作。
action本质就是一个js对象,但约定必须带有type属性,如:
{ type: ACTION_A, // 必须定义 type text}
一般我们都是使用一个函数来返回这个对象体,称之为actionCreator:
//actions.js// actionTypeexport const ACTION_A = 'ACTION_A';export const ACTION_B = 'ACTION_B';// actionCreatorexport let actionCreatorSetWord = (text) => { return { type: ACTION_A, // 必须定义 type text }};// actionCreatorexport let actionCreatorSetList = (list) => { return { type: ACTION_B, // 必须定义 type list }};//action中间件,使dispathc能够接受function对象export let getListData = keyword => dispatch =>{ var apiUrl = REQUEST_URL + encodeURIComponent(keyword); fetch(apiUrl). then( (response) => response.json() ). then( (responseData) => dispatch(actionCreatorSetList(responseData.data.info)) );}
这里的getListData方法,因为请求fetch,是异步action,因此使用了中间件,使dispathc能够接受该action返回的 带dispatch形参的fuc函数(一般dispatch只接受js 对象),中间件在store创建的时候传入,见以下。
2.Reducer
Action 只是描述了有事情发生了这一事实,并没有指明应用如何更新 state。这是 reducer 要做的事情。
reducer要做的是判断action的type,返回新的state,也就是有(previousState, action) => newState 特征的函数。
如果reduer有很多个时,可以使用combineReducers将多个进行合并,先看代码:
//reducers.jsimport { ACTION_A, ACTION_B } from './actions';import { combineReducers } from 'redux';let initialState = { keyword : '我的redux的默认keyword', list : []};//combineReducers使用keyword为key,所以这里的state 其实是 state.keyword,而不再是整个statefunction reducerSetKeyWord(state = initialState.keyword, action) { switch(action.type) { case ACTION_A: // return Object.assign({}, state, action.text); return action.text; } return state;}function reducerSetList(state = initialState.list, action) { switch(action.type) { case ACTION_B: // return Object.assign({}, state, action.list); return action.list; } return state;}//若执行dispath 两个 reduxs都会被调用//combineReducers决定了state的结构let rootReducers = combineReducers({ keyword : reducerSetKeyWord, //key表示了处理state中的哪一部分 reducer方法只需要返回器对应部分的值,若省略key,则取reducer方法名为key list : reducerSetList, });export default rootReducers;
这里使用了combineReducers,而且他还有一个作用,可以决定state的结构,并且在调用reducer(state, action)的时候,参数state默认取的就是其key对应的值
注意:
- 不要修改 state。
- 在 default 情况下返回旧的 state。遇到未知的 action 时,一定要返回旧的 state。
- 如果没有旧的State,就返回一个initialState,这很重要!!!
3.Store
保存state的地方,创建Store非常简单。createStore 有两个参数,Reducer 和 initialState(可选)。
let store = createStore(rootReducers, initialState);
store有四个方法
- getState: 获取应用当前State。
- subscribe:添加一个变化监听器。
- dispatch:分发 action。修改State。
- replaceReducer:替换 store 当前用来处理 state 的 reducer。
react-redux提供了Provider组件,可以用来把根组件包起来,这样,store就可以传递给所有的子组件
子组件中,便可以使用mapStateToProps方法和mapDispatchToProps方法,通过connect把state和dispatch绑定到该组件的props中,
例如,有MyText组件:
//index.ios.jsimport React, { Component } from 'react';import { AppRegistry, StyleSheet, Text, View} from 'react-native';import { createStore, applyMiddleware } from 'redux';import { Provider } from 'react-redux'import thunk from 'redux-thunk';import rootReducers from './src/reducers';import MyText from './src/MyText';let initialState = { keyword : '我的神啊', list : []};let store = createStore( rootReducers, initialState, applyMiddleware(thunk),);export default class ReduxTest extends Component { render() { return ( <Provider store={store}> <View style={styles.container}> <MyText/> </View> </Provider> ); }}const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }});AppRegistry.registerComponent('ReduxTest', () => ReduxTest);
以上代码,这里import thunk from ‘redux-thunk’;引入thunk中间,通过applyMiddleware(thunk)引入。
//MyText.jsimport React, { Component } from 'react';import { AppRegistry, StyleSheet, Text, View, TextInput, ScrollView, Image, FlatList, NavigatorIOS, TouchableHighlight, Button } from 'react-native';import {connect} from 'react-redux';import { bindActionCreators } from 'redux';import * as actionCreators from './actions';const styles = StyleSheet.create({ container: { flex: 1, flexDirection : 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', } });class MyText extends Component { constructor(props) { super(props); } componentDidMount(){ } componentWillUnmount(){ // this.unsubscribe(); } changKeyword = ()=>{ this.props.actionCreatorSetWord("调用actionCreatorSetWord"); this.props.getListData("刘德华"); }; render(){ return ( <View style = {this.styles}> <Text style = {{flex: 1,backgroundColor:'red',top:20,height:20}}>{this.props.keyword}</Text> <Button style = {{flex: 1}} onPress = {this.changKeyword} title = "点我" /> <FlatList style = {{flex: 1,backgroundColor: 'green'}} data={this.props.datalist} renderItem={ ({item}) => ( <Text>{item.filename}</Text> ) } /> </View> ); }}function mapStateToProps(state) { return { keyword: state.keyword , datalist:state.list};}//若不connect,默认直接返回dispatchfunction mapDispatchToProps(dispatch) { //dispatch为store传过来的 return bindActionCreators(actionCreators, dispatch); //将dispatch绑定到所有的actionCreator上 //@return {actionCreator方法名: (parameter) => dispatch(actionCreator(parameter)))} 本质就是对所有actionCreator的实现套上dispatch,key为Creator名,connect则把这个key绑定到pros上}// 最终暴露 经 connect 处理后的组件export default connect(mapStateToProps,mapDispatchToProps)(MyText);
这里 mapStateToProps返回的对象会直接设置到props上
mapDispatchToProps方法中使用了一个bindActionCreators方法,可以将actions.js中多个action方法绑定到dispatch上,本质就是对所有actionCreator的实现套上dispatch,key为Creator名,connect则把这个key绑定到pros上,类似{actionCreator方法名: (parameter) => dispatch(actionCreator(parameter)))}
,通过mapDispatchToProps返回,映射到改组件的props上,便可以直接通过this.props.getListData直接调用action
4.总结
综上,可以整理出Store、Reducer、Action三者的关系,store是管理协调着reducer、action、state。
store创建的时候传入了reducer,提供dispatch方法,因此通过store.dispatch(action)修改state,dispatch知道action该传给哪个reducer,更新什么state。所以,到最后,我们的更新操作简化成dispatch(action)的形式
摘录参考:
https://github.com/berwin/Blog/issues/4
http://cn.redux.js.org/docs/recipes/reducers/PrerequisiteConcepts.html
https://reactnative.cn/docs/0.50/getting-started.html
- react-native + redux 实践
- React-native Redux 干货分享实践
- react native redux
- react native redux counter
- react-native redux debug
- React Native集成Redux
- React Native 之 Redux
- react native and redux
- react-native redux学习心得
- React Native 集成 Redux
- React-Native 之 redux 与 react-redux
- React-Native 之 redux 与 react-redux
- react-native,redux,redux-saga组合开发
- react native 中 使用 Redux
- react-native添加redux支持
- react-native添加redux支持
- react-native 之redux install
- React Native架构之Redux
- 学术论文地址总结
- React学习笔记_按需加载
- Spark算子:RDD基本转换操作(1)–map、flagMap、distinct
- 二叉树的遍历方法及递归实现
- 服务端开发之MySql数据库问题记录
- react-native + redux 实践
- Python学习之路002
- 使用LVS实现负载均衡原理及安装配置详解
- Eclipse SVN冲突详细解决方案
- Bezier曲线在Android动画中的应用
- Linux部署Apache
- mount如果没有指定-t会怎么样?
- 【水题】 hdu 2022 海选女主角
- SpringBoot构建微服务实战 之 Profile决策