我试图通过使用React Native做一个非常简单的项目来熟悉 React Native 。我希望代码干净并且遵循一些体系结构。我已经将 Flux与React 一起使用了一段时间,并认为我也可以对 React Native 做同样的事情。如果我在这里错了,请告诉我为什么不可能吗?
假设我是对的,让我介绍一下我所面临的实际问题。我正在遵循 CRNA 教程,并使用 Expo 进行构建和测试。遵循 Flux 体系结构。这就是我所做的。
使用npm install flux
使用以下代码创建了dispatcher.js
文件。
import { Dispatcher } from 'flux';
export default new Dispatcher();
创建了一个执行以下操作的“ sampleactiondispatcher.js”:
import Dispatcher from '../actiondispatchers/dispatcher';
import ActionType from '../actiondispatchers/actiontype';
class SampleActionDispatcher {
saveSomething(value) {
Dispatcher.dispatch({
actionType: ActionType.SAMPLE_ACTION,
payload: value
});
}
}
export default new SampleActionDispatcher();
创建了一个商店,该商店已注册了对调度员的回调samplestore.js
import { EventEmitter } from 'events';
import Dispatcher from '../actiondispatchers/dispatcher';
import ActionType from '../actiondispatchers/actiontype';
// Constants
const SAMPLE_EVENT = 'SampleEvent';
class SampleStore extends EventEmitter {
constructor() {
super();
// Registering the callback
Dispatcher.register(this.dipatcherCallback.bind(this));
}
dipatcherCallback(action) {
switch (action.actionType) {
case ActionType.SAMPLE_ACTION:
this.emit(SAMPLE_EVENT);
break;
}
}
}
export default new SampleStore();
以下是触发操作samplecomponent.js
import React from 'react';
import { StyleSheet,
Dimension,
TextInput,
View,
Text,
Button,
KeyboardAvoidingView } from 'react-native';
import SampleActionDispacther from '../../actiondispatchers/sampleactiondispatcher';
let screenWidth = Dimensions.get('window').width;
export default class SampleComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
textValue: ''
};
}
render() {
return (
<KeyboardAvoidingView id='sampleComponentHolder' style={styles.editorContainer} behavior='padding' enabled>
<View id='formFieldsHoldder' style={{paddingTop: 20}}>
<TextInput
id='textField1'
style={[styles.textStyle, styles.input]}
underlineColorAndroid = 'transparent'
placeholderTextColor='rgba(14,194,145,1)'
placeholder='Enter something'
keyboardType='numeric'
value={this.state.textValue}
onChangeText={(text) => this.setState({textValue: text})}
/>
<Button
id='saveButton'
color='rgba(46,107,138,1)'
title='Save'
onPress={this.onPressingSaveButton}
/>
</View>
</KeyboardAvoidingView>
);
}
/**
* On pressing the save button
*/
onPressingSaveButton =() => {
if (this.state.textValue !== '') {
SampleActionDispacther.saveSomething(Number(this.state.textValue));
} else {
alert('Oops! I dont think you have provided any values for saving.');
}
}
}
// Styles
const styles = StyleSheet.create({
editorContainer: {
flexDirection: 'column',
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
textStyle: {
color: 'rgba(14,194,145,1)',
fontFamily: 'monospace',
fontSize: 16,
textAlign: 'center'
},
input: {
height: 40,
width: (90 * screenWidth)/100,
borderWidth: 1
}
});
让我认为Flux不能与react native一起使用的真正问题是,每当我单击“保存”按钮时,调度的操作都无法到达商店。如果有人可以弄清楚为什么会这样。还是我编写的代码有问题?