2016-11-06 83 views
0

我正在使用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的状态。

如果我构建应用程序的方式完全是疯狂的,那么我全都是耳朵。

回答

2

而不是API作为“模块”,尝试使用它作为中间件。因此,您将有权访问您的上下文中的dispatch()。

这个想法是调度行动,并根据您的中间件将“决定”调用您的API的行动。如果发生错误,中间件可以发送默认的错误操作。

这篇文章可以帮助你:http://www.sohamkamani.com/blog/2016/06/05/redux-apis/

您还可以使用终极版的API中间件:https://github.com/agraboso/redux-api-middleware

+0

谢谢你,让我在正确的道路上。这很有意义。 – Mattis

相关问题