2016-10-05 31 views
0

我有這樣的代碼,返回一個thunk爲我的API從反應-Redux的形式調用的thunk提交處理

import { SUBSCRIBE_REQUEST, SUBSCRIBE_SUCCESS, SUBSCRIBE_FAILURE } from '../../constants' 

export function subscribeUser (data) { 
    return (dispatch, getState, { axios }) => { 

    dispatch({ type: SUBSCRIBE_REQUEST }) 
    return axios.get(`some/api/call`, data) 
     .then(res => { 
     dispatch({ 
      type: SUBSCRIBE_SUCCESS, 
      payload: res.data 
     }) 
     }) 
     .catch(error => { 
     dispatch({ 
      type: SUBSCRIBE_FAILURE, 
      payload: error, 
      error: true 
     }) 
     }) 
    } 
} 

我現在推行react-redux-form和我如何OT上述與提交功能連接不清楚。從自己的文件,預計我通過在提交行動承諾:

class myForm extends React.Component { 

    handleSubmit (data) { 
    const { dispatch } = this.props 
    dispatch(actions.submit('user', somePromise)) 

    } 

基本上是這樣的:

dispatch(actions.submit('user', subscribeUser)) 

如何我可以提交處理程序連接我thunked API代碼?我已經看過redux-promise作爲一種可能性,雖然我不清楚它會解決我的問題,並且還想保留現有的代碼庫,如果我可以工作。

回答

0

注意:該示例與React-Native一樣,但它作爲React組件工作,因爲還原器和操作相同。

隨着react-redux,您可以使用connectactions和的reducersclass你想 隨着redux可以綁定動作到你的行動props鏈接。它看起來那樣

import React, { Component, PropTypes } from 'react'; 
import { View } from 'react-native'; 
import { User, Button, Header } from '../components'; 
import { connect } from 'react-redux'; 
import { bindActionCreators } from 'redux';  

import * as app from '../../actions/appActions'; 

class Home extends Component { 

    componentWillMount() { 
     this.props.actions.load(); //This will call the actions load. this.props.action will contain subscribeUser if you declare in down mapDispatchToProps 
    } } 

    //Whatever the render 
    render() { 
     return (
      <View /> 
     ); 
    } 
} 
//PROPS VALIDATION 
Home.propTypes = { 
    users: PropTypes.object.isRequired, 
    actions: { 
     load: PropTypes.func.isRequired, 
    }, 
}; 
//LINK STATE FROM REDUCER TO THIS CLASS. NEED TO DO PROPS VALIDATION 
function mapStateToProps(state) { 
    return { 
     users: state.app.users, 
    }; 
} 

//LINK ACTIONS TO THE CLASS SO YOU CAN USE IT LIKE IF IT WAS A PROPS. NEED TO DO PROPS VALIDATION 
function mapDispatchToProps(dispatch) { 
    return { 
     actions: bindActionCreators(app, dispatch), 
    }; 
} 

//CONNECT PROPS AND ACTION TO COMPONENT AS PROPS 
export default connect(mapStateToProps, mapDispatchToProps)(Home); 

基本上,這把一個高階組件的組件

相關問題