学习 redux 中。。。网上很多的例子都是在网页端实现的,我想在 react-native 上跑通
新建 ReactNative 项目
index.ios.js 文件代码
import React, {Component} from 'react';
import {AppRegistry, StyleSheet, Text, View} from 'react-native';
import {createStore} from 'redux';
import {Provider} from 'react-redux';
import {reducers} from './src/reducer';
import {App} from './src/App';
const store = createStore(reducers)
export default class rnredux extends Component {
render() {
return (
<View style={styles.container}>
<Provider store ={store}>
<App/>
</Provider>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF'
},
});
AppRegistry.registerComponent('rnredux', () => rnredux);
App.js 文件代码
import {connect} from 'react-redux';
import MyComponent from './myComponent';
function mapStateToProps(state) {
return {text: state.text, name: state.name}
}
function mapDispatchToProps(dispatch) {
return {
onChange: (e) => dispatch({type: 'change', payload: e.target.value})
}
}
const App = connect(
mapStateToProps,
mapDispatchToProps
)(MyComponent);
export default App;
myComponent.js 文件代码
import React,{Component} from 'react';
import {Text,TextInput} from 'react-native';
export default class myComponent extends Component{
render(){
<View>
<Text>{this.props.text}</Text>
<TextInput defaultValue = {this.props.name} onChangeText = {this.props.onChange}></TextInput>
</View>
}
}
reducer.js 文件代码
import {combineReducers} from 'redux';
const reducerAction = (state = {
text: '你好,访问者',
name: '访问者'
}, action) => {
switch (action.type) {
case 'change':
return {
name: action.payload,
text: '你好,' + action.payload
};
default:
return state;
}
}
const reducers = combineReducers({
reducerAction
})
export default reducers;
例子应该实现的效果类似双向数据绑定。
示例代码的网页版本在浏览器上能够正常运行,但是 RN 版本上的IOS模拟器一直报错 Expected the reducer to be a function.在 Stack Overflow 中查过相关问答,均无法解决。英文水平有限,想现在 segmentFault 上问问看,有没有大神能够解决?