我正在使用Redux方法在React Native中构建应用程序。如何从我的API模块派发一个redux动作?
我希望能够从我的API“模块”调度操作。
潜在地,每个API请求都可能超时(或失败),如果发生这种情况,我想分配一个动作给我的全局reducer(它处理errorBar消息和状态)。我宁愿不在场景或组件内部为每个结果(每个API请求)分发该消息。
我的结构如下(剥离最含量):
index.android.js
import React from 'react';
import { AppRegistry } from 'react-native';
import configureStore from './app/store/configureStore'; // combines all reducers
const store = configureStore();
import RootContainer from './app/containers/rootContainer';
import { Provider } from 'react-redux';
const App =() => (
<Provider store={store}>
<RootContainer/>
</Provider>
);
// Register our app
AppRegistry.registerComponent('ReduxTest',() => App);
rootContainer:
import { connect } from 'react-redux';
import RootScene from '../components/scenes/RootScene';
import { hideSplash, showSplash, setSplashMessage } from '../actions/splashActions';
function mapStateToProps(state) {
return {
global: state.globalReducer,
splash: state.splashReducer
};
}
export default connect(
mapStateToProps,
{
hideSplash:() => hideSplash(),
showSplash:() => showSplash(),
setSplashMessage: (message) => setSplashMessage(message)
}
)(RootScene);
RootScene.js
import React, { Component } from 'react';
import Splash from '../views/Splash';
import ErrorBar from '../elements/ErrorBar';
import { View, Text, StyleSheet } from 'react-native';
import api from '../../helpers/api';
class RootScene extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentWillMount() {
api.checkConnectivity().then(response => {
// Hide splash, etc, optimally error states could be handled inside of "api"
});
}
render() {
return (
<View style={styles.rootWrapper}>
<ErrorBar props={this.props.global.errorBar}/>
<Splash/>
</View>
);
}
}
const styles = StyleSheet.create({
rootWrapper: {
flex: 1
}
});
export default RootScene;
api.js
const api = {
checkConnectivity() {
return _buildRequest({ endpoint: '/version' }).then(_makeRequest);
}
};
module.exports = api;
const _buildRequest = (request_data) => {
// ...
};
const _makeRequest = (request_object) => {
// ...
};
我知道,我去掉了上面的代码缺少的行动来改变errorBar的状态。
如果我构建应用程序的方式完全是疯狂的,那么我全都是耳朵。
谢谢你,让我在正确的道路上。这很有意义。 – Mattis