我正在使用Redux方法在React Native中构建应用程序。
我希望能够从我的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状态的操作。
如果我构建应用程序的方式完全疯了,我全都听见了。
答案 0 :(得分:2)
而不是API作为&#34;模块&#34;,尝试将其用作中间件。因此,您可以访问上下文中的dispatch()。
这个想法是根据您的中间件将决定&#34;决定&#34;打电话给你的api。如果出现错误,中间件可以调度您的默认错误操作。
这篇文章可能会对您有所帮助:http://www.sohamkamani.com/blog/2016/06/05/redux-apis/
您也可以使用redux-api-middleware:https://github.com/agraboso/redux-api-middleware
答案 1 :(得分:2)
您可以使用Thunk Middleware执行此操作。
http://blog.nojaf.com/2015/12/06/redux-thunk/ https://github.com/gaearon/redux-thunk