0

我有这段代码为我的 API 返回一个 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,但不清楚如何将上述内容与提交功能联系起来。从他们的文档中,它希望我在提交操作中传递一个承诺:

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将其视为一种可能性,但我不清楚它是否可以解决我的问题,并且如果我可以使用它,我还想保留现有的 thunk 代码库。

4

1 回答 1

0

注意:该示例使用 React-Native,但它作为 React 组件工作,因为 reducer 和操作是相同的。

使用react-redux,您可以使用将和connect链接到您想要的 使用您可以将操作绑定到您的操作。看起来会这样actionspropsreducersclassredux

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);

基本上,这在组件周围放置了一个高阶组件

于 2016-10-06T04:07:36.517 回答