首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从react-redux-form提交处理程序调用thunk

从react-redux-form提交处理程序调用thunk
EN

Stack Overflow用户
提问于 2016-10-06 07:29:09
回答 1查看 897关注 0票数 0

我有这个代码,它为我的API返回一个thunk

代码语言:javascript
复制
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,不清楚如何将上面的内容与提交函数连接起来。从他们的文档中,它希望我在提交操作中传递一个承诺:

代码语言:javascript
复制
class myForm extends React.Component {

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

  }

基本上是这样的:

代码语言:javascript
复制
 dispatch(actions.submit('user', subscribeUser))

如何将我的thunked API代码与提交处理程序连接起来?我已经考虑过redux-promise作为一种可能性,尽管我不清楚它是否能解决我的问题,如果我能工作的话,我也想保留现有的thunk代码库。

EN

回答 1

Stack Overflow用户

发布于 2016-10-06 12:07:37

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

使用react-redux,您可以使用connectactionsreducersprops链接到您想要的class。使用redux,您可以将操作绑定到您的操作。看起来是这样的

代码语言:javascript
复制
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);

基本上,这在组件周围放置了一个更高级别的组件

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39885229

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档