react-native + redux 实践
一、rn环境搭建看我的另外一篇文章 http://www.52php.cn/article/p-etqhadrj-bqb.html 二、rn起步对于RN的时候,通过https://reactnative.cn/docs/0.50/getting-started.html 可知道,通过react-native引入组件,可在Component中的render方法使用JSX标签如Text、View、FlatList,通过 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重绘,典型的状态机机制。 三、使用reduxredux中有三个基本概念,Action,Reducer,Store。 1.ActionActions 是把数据从应用传到 store 的有效载荷。它是 store 数据的唯一来源。用法是通过 store.dispatch() 把 action 传到 store。 Action 有两个作用:
{ type: ACTION_A,// 必须定义 type text }
一般我们都是使用一个函数来返回这个对象体,称之为actionCreator: //actions.js
// actionType
export const ACTION_A = 'ACTION_A';
export const ACTION_B = 'ACTION_B';
// actionCreator
export let actionCreatorSetWord = (text) => {
return {
type: ACTION_A,// 必须定义 type
text
}
};
// actionCreator
export 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.ReducerAction 只是描述了有事情发生了这一事实,并没有指明应用如何更新 state。这是 reducer 要做的事情。 //reducers.js
import { ACTION_A,ACTION_B } from './actions';
import { combineReducers } from 'redux';
let initialState = {
keyword : '我的redux的默认keyword',list : []
};
//combineReducers使用keyword为key,所以这里的state 其实是 state.keyword,而不再是整个state
function 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({},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对应的值 注意:
3.Store保存state的地方,创建Store非常简单。createStore 有两个参数,Reducer 和 initialState(可选)。 let store = createStore(rootReducers,initialState);
store有四个方法 react-redux提供了Provider组件,可以用来把根组件包起来,这样,store就可以传递给所有的子组件 //index.ios.js
import React,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.js
import React,{ Component } from 'react';
import {
AppRegistry,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',}
});
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,默认直接返回dispatch
function 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上 4.总结综上,可以整理出Store、Reducer、Action三者的关系,store是管理协调着reducer、action、state。 摘录参考: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |