2016-11-06 86 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

相關問題