最近被redux搞得晕头转向的,总算弄了个可以实现的效果了
添加依赖
npm install --save redux
npm install --save react-redux
在装好这两个依赖后坑了我一把,一直报错找不到该模块,最后把全部modules删掉重新install才行
项目结构
Action代码
/**
* Created by Administrator on 2017/12/26.
*/
export const ADD_TEXT = 'ADD_TEXT';
/**
* 数据处理,可以是网络数据本地数据
* @param text
* @returns {{type: string, text: *}}
*/
export function addTextAction(text) {
return {
type: ADD_TEXT,
text
}
}
Reducer代码
/**
* Created by Administrator on 2017/12/26.
*/
import { ADD_TEXT } from './Action'
const initialState = {
text: '444'
};
// 具体业务逻辑在这里处理
export default function addTextReducer(state = initialState, action) {
switch (action.type) {
case ADD_TEXT:
return Object.assign({}, state, {
text: action.text
});
default:
return state
}
}
app入口
import React from 'react';
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import Main from './Main'
import Reducer from './rx/Reducer'
let store = createStore(Reducer);
export default class App extends React.Component {
render() {
return (<Provider store={store}>
<Main />
</Provider>)
}
}
容器
import React from 'react';
// 引入布局View
import {StyleSheet, View, Text, Button} from 'react-native';
import { connect } from 'react-redux'
import Module from './Mobule'
import {addTextAction} from './rx/Action'
/**
* 容器,这里放组件,以及逻辑处理
* 在组件中只做界面的展示
*/
class Main extends React.Component {
constructor(props) {
super(props);
}
render() {
const {text, onChangeText} = this.props;
console.log('==='+JSON.stringify(this.props));
return (
<View style={styles.container}>
<Module text={text} onChangeText={onChangeText}/>
</View>
);
}
}
const styles = StyleSheet.create({});
// 哪些state中的值是要传递到组件中的
function mapStateToProps(state) {
return {
text: state.text
};
}
// 哪些 action 创建函数是我们想要通过 props 获取的?
function mapDispatchToProps(dispatch) {
return {
onChangeText: () =>dispatch(addTextAction(new Date().getMilliseconds())) // 左侧的onChangeText是在组件中调用的 右侧dispatch(action)
};
}
// 包装 component ,注入 dispatch 和 state 到其默认的 connect(select)(App) 中;
export default connect(mapStateToProps,mapDispatchToProps)(Main)
组件
import React from 'react';
// 引入布局View
import {StyleSheet,Text,Button, View} from 'react-native';
/**
* 组件
*/
export default class Mobule extends React.Component {
render() {
const {text, onChangeText} = this.props;
return (
<View style={styles.container}>
<Text>
我是组件中的{text}
</Text>
<Button title="Mobule的点我啊" onPress={onChangeText}/>
</View>
);
}
}
const styles = StyleSheet.create({});
最终实现效果:点击按钮改变text的值,并更新到组件显示